首页 > 其他 > 详细

【树】Binary Tree Right Side View

时间:2016-02-07 02:18:31      阅读:130      评论: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.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function(root) {
    var res=[];
    if(root==null){
        return res;
    }
    
    var queue=[];
    queue.push(root);
    
    while(queue.length!=0){
        for(var i=0,len=queue.length;i<len;i++){
            var cur=queue.pop();
            if(cur.right){
                queue.push(cur.right);
            }
            if(cur.left){
                queue.push(cur.left);
            }
        }
        res.push(cur.val);
    }
    
    return res;
};

 

【树】Binary Tree Right Side View

原文:http://www.cnblogs.com/shytong/p/5184455.html

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