Leetcode 199(Java)

来源:互联网 发布:简支梁配筋计算软件 编辑:程序博客网 时间:2024/06/15 10:53

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

一开始以为这题很简单,只要顺着最右往下先右后左就可以,事实说明刚睡醒了脑子不是很清楚,忽略了层数不一,左边子树的深度大于右边,从而也可以看见根的左子树的某些结点的情况。调整思路后,其实List中元素的个数是我们现在所看见的最大层数,可以与它作比较,如果等于它,这个结点可以加进来(假定层数从0开始),注意顺序,先右后左。AC码如下:

public class Solution {    public List<Integer> rightSideView(TreeNode root) {        List<Integer> result = new ArrayList<Integer>();        findRightView(root,result,0);        return result;    }    private void findRightView(TreeNode root,List<Integer> result,int depth){        if(root==null)return;        if(depth==result.size())result.add(root.val);        findRightView(root.right,result,depth+1);        findRightView(root.left,result,depth+1);    }}
0 0
原创粉丝点击