您的位置:首页 > 其它

[LeetCode]199. Binary Tree Right Side View

2016-03-13 11:48 211 查看
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]
.

思路:层序遍历二叉树,把每一层的最后一个节点存进结果list中

/**
* Definition for a binary tree node.
* 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;
int thislevel = 1;
int nextlevel = 0;
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while(q.isEmpty() == false) {
while(thislevel > 0) {
TreeNode temp = q.poll();
thislevel--;
if (thislevel == 0) res.add(temp.val);
if(temp.left != null) {
nextlevel++;
q.offer(temp.left);
}
if(temp.right != null) {
nextlevel++;
q.offer(temp.right);
}
}
thislevel = nextlevel;
nextlevel = 0;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: