[LeetCode] Binary Tree Right Side View

王朝学院·作者佚名  2016-05-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

[LeetCode] Binary Tree Right Side ViewGiven a binary tree, imagine yourself standing on therightside 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].

最近感觉做了好多和BTS有关的题哈哈。

这道题个人感觉难度还好。用两个list来解决就好。一个用来store结果,另一个则是用来loop。

这道题其实就是写一个算法从树头到数尾一一排查,只不过我们一定要想到有时候左边长度会比右边长,所以你在右边,也是可以看到左边的比右边长的那部分的node的。所以我们不能只关注右侧。

但算法运行的时候我们肯定要先观察右边,所以往排查的list里面加元素的时候先add的一定是右边的,这样只要右边有,那么最先看到的一定是右边的那个。然后接下来再是左边。这样一想,就会简单很多了。

/** * 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) { ArrayList<Integer> result=new ArrayList<Integer>(); if(root==null){ return result; } LinkedList<TreeNode> count=new LinkedList<TreeNode>(); count.add(root); while(count.size()>0){ int size=count.size(); for(int i=0;i<size;i++){ TreeNode test=count.remove(); if(i==0){ result.add(test.val); } if(test.right!=null){ count.add(test.right); } if(test.left!=null){ count.add(test.left); } } } return result; }}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航