码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Binary Tree Right Side View

时间:2015-08-13 09:56:37      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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].

 

     最近感觉做了好多和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;
    }
}

 

[LeetCode] Binary Tree Right Side View

标签:

原文地址:http://www.cnblogs.com/orangeme404/p/4726296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!