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,
You should return
这是一个很有趣的题目,一开始我的思路是进行层序遍历,然后取每一层最右边的数字,但是在参考了别人的代码后,发现自己真是太笨了,他们的解决思路很巧妙。
代码如下:
这个方法采用了递归实现,helper有三个参数传入,一个是当前visit的节点,一个是存储结果的list,还有就是代表当前遍历到哪一层的lvl。这个题目实际上就是找出每一层最靠右边的节点,因此每一层只取一个数。当访问一个节点时,如果发现当前层数比list.size()大,那个这个节点就是最右边的节点,并把该节点加入到list中,然后从该节点的右子树向下递归,再从该节点的左子树向下递归。
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中,然后从该节点的右子树向下递归,再从该节点的左子树向下递归。
相关文章推荐
- golang gc 问题(转的)
- 050666 获取tableview的cell
- C++课堂作业(1)
- hash加密 python
- 【代码笔记】判断字符串是否为空
- 字符串的排列
- Segment fault的一种处理方法
- 【代码笔记】iOS-判断字符串是否为空
- Android网络类型判断(2g、3g、wifi)
- 应用层
- Node.js插件安装图文教程
- socket 笔记(一)
- 解决Ext.form.DateField在浏览器中显示可能有问题
- JS学习7(BOM)
- 关于UIImage图片类别-裁剪图片和等比例缩放图片实现
- android 基础 HashMap,TreeMap排序
- 苹果:所有应用必须支持IPv6-only网络
- 解决eclipse的 Invalid project description. overlaps the location of another project: 问题
- tomcat压缩配置
- tomcat压缩配置