LeetCode OJ 199. 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].

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

代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<Integer> rightSideView(TreeNode root) {
12         List<Integer> result = new ArrayList<Integer>();
13         if(root == null){
14             return result;
15         }
16         helper(root, result, 1);
17 
18         return result;
19     }
20     private void helper(TreeNode root, List<Integer> list, int lvl){
21         if(root == null){
22             return;
23         }
24         if(list.size() < lvl){
25             list.add(root.val);
26         }
27         helper(root.right, list, lvl + 1);
28         helper(root.left, list, lvl + 1);
29     }
30 }

这个方法采用了递归实现,helper有三个参数传入,一个是当前visit的节点,一个是存储结果的list,还有就是代表当前遍历到哪一层的lvl。这个题目实际上就是找出每一层最靠右边的节点,因此每一层只取一个数。当访问一个节点时,如果发现当前层数比list.size()大,那个这个节点就是最右边的节点,并把该节点加入到list中,然后从该节点的右子树向下递归,再从该节点的左子树向下递归。

原文地址:https://www.cnblogs.com/liujinhong/p/5464492.html