zoukankan      html  css  js  c++  java
  • 【树】Binary Tree Right Side View

    题目:

    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;
    };
  • 相关阅读:
    绿豆加速器
    电脑派位系统(新生入学摇号) v2016
    硬盘安装win10
    msbuild
    async
    win sshd
    Ftp软件
    nginx basic auth 登陆验证模块
    深入理解docker的link机制
    Docker Compose to CoreOS
  • 原文地址:https://www.cnblogs.com/shytong/p/5184455.html
Copyright © 2011-2022 走看看