【树】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;
};
原文地址:https://www.cnblogs.com/shytong/p/5184455.html