标签:leetcode
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,
1 <---
/ 2 3 <---
\ 5 4 <---
You should return [1, 3, 4].
Credits:
Special thanks to
@amrsaqr for adding this problem and creating all test cases.
很简单的一道题,题目要求是,假如站在树的右侧,那么可以看到哪些元素,意思就是记录每一层最右边的元素。所以很自然想到了层次遍历,这样可以对每一层都单独处理。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
//利用层次遍历,然后每一层最后进入队列的就是右边可以看到的
int count = 0;//记录每一层的元素数;
List<Integer> list = new ArrayList<Integer>();//记录看到的元素
Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列,进行遍历使用
if(root == null){
return list;
}
count++;
queue.offer(root);
while(true){
int next = 0;//记录下一层的元素数
while(count > 0){//将本层的元素移除队列,同时将下一层的元素加入队列
TreeNode tmp = queue.poll();//移除队首元素
count--;
if(count == 0){//count层的最后一个元素
list.add(tmp.val);
}
if(tmp.left != null){//左子树不空
queue.offer(tmp.left);
next++;
}
if(tmp.right != null){
queue.offer(tmp.right);
next++;
}
}
if(next == 0){//如果队列为空,则遍历完毕
break;
}else{
count = next;//更新为下一层的元素数
}
}
return list;
}
}标签:leetcode
原文地址:http://blog.csdn.net/havedream_one/article/details/44905243