首页 > 学院 > 开发设计 > 正文

[LeetCode] Binary Tree Right Side View

2019-11-15 01:07:21
字体:
来源:转载
供稿:网友
[LeetCode] Binary Tree Right Side View

Given 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;    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表