您的位置:首页 > 其它

LeetCode OJ 199. Binary Tree Right Side View

2016-05-06 09:41 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]
.

这是一个很有趣的题目,一开始我的思路是进行层序遍历,然后取每一层最右边的数字,但是在参考了别人的代码后,发现自己真是太笨了,他们的解决思路很巧妙。

代码如下:

/**
* 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> result = new ArrayList<Integer>();
if(root == null){
return result;
}
helper(root, result, 1);

return result;
}
private void helper(TreeNode root, List<Integer> list, int lvl){
if(root == null){
return;
}
if(list.size() < lvl){
list.add(root.val);
}
helper(root.right, list, lvl + 1);
helper(root.left, list, lvl + 1);
}
}


这个方法采用了递归实现,helper有三个参数传入,一个是当前visit的节点,一个是存储结果的list,还有就是代表当前遍历到哪一层的lvl。这个题目实际上就是找出每一层最靠右边的节点,因此每一层只取一个数。当访问一个节点时,如果发现当前层数比list.size()大,那个这个节点就是最右边的节点,并把该节点加入到list中,然后从该节点的右子树向下递归,再从该节点的左子树向下递归。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: