您的位置:首页 > 其它

[LeetCode]Binary Tree Right Side View

2015-04-06 17:36 267 查看
原题链接:https://leetcode.com/problems/binary-tree-right-side-view/

题意描述:

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]
.

题解:

这道题非常有趣,是找二叉树从右侧看的时候能看到的数,其实思路也是很简单,即返回每一层的最右边的一个数就好了,在二叉树的层序遍历的代码上稍作修改即可。对二叉树的层序遍历不太清楚的朋友,可看我之前的博客《二叉树完全总结》。具体没什么好说的,直接上代码:

/**
* 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) {
List<Integer> res = new ArrayList<Integer>();
if(root==null)
return res;
Queue<TreeNode> Q = new LinkedList<TreeNode>();
Q.offer(root);
int curLevel = 1;
res.add(root.val);
while(!Q.isEmpty()){
int levelSize = Q.size();
int count = 0;
TreeNode last = null;
while(count<levelSize){
TreeNode p = Q.poll();
if(p.left!=null){
last = p.left;
Q.offer(p.left);
}
if(p.right!=null){
last = p.right;
Q.offer(p.right);
}
count++;
}
if(last!=null)
res.add(last.val);

}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: