199. Binary Tree Right Side View

来源:互联网 发布:java什么是方法的定义 编辑:程序博客网 时间:2024/06/14 01:13

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的大小等于层数;

利用这个特点来判断遍历到的值是否需要加到list中去,


public class Solution {    List<Integer> list=new ArrayList<Integer>();    public List<Integer> rightSideView(TreeNode root) {            if(root!=null) right(root,0);            return list;    }    public void right(TreeNode root,int level){        if(root==null) return ;        if(level==list.size()) list.add(root.val);        right(root.right,level+1);        right(root.left,level+1);            }}


0 0