199. Binary Tree Right Side View

来源:互联网 发布:剪刀手软件 编辑:程序博客网 时间:2024/05/22 18:56

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


BFS,记录下每层的节点数,将最后一个节点的值加到list中。

public class Solution {    public List<Integer> rightSideView(TreeNode root) {        if(root==null) return new ArrayList<>();        Queue<TreeNode>  queue=new LinkedList<>();        List<Integer> list=new ArrayList<>();        int count=1,prv_count=0;        queue.add(root);        while(!queue.isEmpty()){            prv_count=count;            count=0;            while(prv_count>0){                TreeNode node=queue.poll();                if(--prv_count==0){                    list.add(node.val);                }                if(node.left!=null){                    queue.add(node.left);                    count++;                }                if(node.right!=null){                    queue.add(node.right);                    count++;                }            }        }        return list;    }}




0 0
原创粉丝点击