首页 > 其他 > 详细

[leedcode 199] Binary Tree Right Side View

时间:2015-08-03 22:15:31      阅读:179      评论:0      收藏:0      [点我收藏+]

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

/**
 * 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) {
        //层序遍历,每次获取每一层最后的节点,并将其保存在结果
        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
        List<Integer> res=new ArrayList<Integer>();
        if(root==null) return res;
        queue.add(root);
        while(!queue.isEmpty()){
            int count=queue.size();
            res.add(queue.get(count-1).val);
            for(int i=0;i<count;i++){
                TreeNode temp=queue.remove();
                if(temp.left!=null)
                queue.add(temp.left);
                if(temp.right!=null)
                queue.add(temp.right);
            }
        }
        return res;
    }
}

 

[leedcode 199] Binary Tree Right Side View

原文:http://www.cnblogs.com/qiaomu/p/4700367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!