Binary Tree Right Side View

来源:互联网 发布:自古枪兵幸运e 知乎 编辑:程序博客网 时间:2024/05/17 01:43

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

思路:从右边看过去能看到的结点,也就是每一层最右边的结点,那么按照层序遍历,每一次遇到最右边的结点的时候就把它放到结果集中,可以用一个count来记录每一层的结点数。

/** * 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) {        List<Integer> result=new ArrayList<Integer>();        if(root==null) return result;        ArrayDeque<TreeNode> queue=new ArrayDeque<TreeNode>();        queue.add(root);        while(!queue.isEmpty())        {               TreeNode temp=null;            int count=queue.size();            for(int i=0;i<count;i++)            {   temp=queue.poll();                if(i==count-1)                  {                      result.add(temp.val);                  }                if(temp.left!=null)                   queue.add(temp.left);                if(temp.right!=null)                 queue.add(temp.right);            }        }        return result;    }}
0 0
原创粉丝点击