Binary Tree Right Side View
2015-08-16 09:53
246 查看
Given a binary tree, imagine yourself standing on the right side of it, return the
values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
You should return [1, 3, 4].
使用一个队列,先放右子树,再放左子树,取每一层的第一个出队列元素。
values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4].
使用一个队列,先放右子树,再放左子树,取每一层的第一个出队列元素。
public List<Integer> rightSideView(TreeNode root) { List<Integer> result=new ArrayList<Integer>(); if(root==null) return result; Queue<TreeNode> queue=new LinkedList<TreeNode>(); queue.add(root); while(!queue.isEmpty()){ int size=queue.size(); for(int i=0;i<size;i++){ TreeNode node=queue.poll(); if(i==0) result.add(node.val); if(node.right!=null) queue.add(node.right); if(node.left!=null) queue.add(node.left); } } return result; }
相关文章推荐
- Android studio百度地图(一)
- Talk the Talk
- Engineer in the White Spaces
- Linux用户添加root权限
- Codeforces Round #261 (Div. 2) D. Pashmak and Parmida's problem (树状数组求逆序数 变形)
- linux下lv卷的扩展
- css样式简介
- Java日志框架——不同日志框架转换,日志记录请求的Level值不能一一映射
- 网络编程TCP(四)
- iOS应用中增加emoji表情输入功能
- It’s All About Performance
- du命令 实现Linux 某个文件夹下的文件按大小排序
- Java NIO系列教程(三) Buffer
- UIPageControl
- POJ 2699 The Maximum Number of Strong Kings
- Linux学习笔记-----RPM包管理----yum在线管理之使用setup配置IP
- The New Villa (Uva 321 bfs)
- http 206 Range -- 端点续传(resumed download) -- POST/PUT/DELETE
- shape和selector和layer-list的(详细说明)
- 再谈工厂三姐妹