您的位置:首页 > 其它

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,

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