AwesomeDevin / blog

Welcome to Devin's blog,I'm trying to be a fullstack developer and sticking with it !!!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

二叉树右视图实现

AwesomeDevin opened this issue · comments

给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
image
输入: [1,2,3,null,5,null,4]
输出: [1,3,4]

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */


// 广度优先
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function(root) {
    let res=[],queue=[];
    queue.push(root);
    
    while(queue.length && root){
        let len = queue.length
        while(len){
            const node = queue.shift()
            if(len === 1) res.push(node.val)
            node.left && queue.push(node.left)
            node.right && queue.push(node.right)
            len--
        }
    }

    return res
}



// 深度优先
var rightSideView = function(root) {
    const res = []
    function dfs(node, depth){
        if(!node) return
        if(res.length === depth){
            res.push(node.val);
        }
        dfs(node.right, depth + 1)
        dfs(node.left, depth + 1)
    }
    dfs(root, 0)
    return res
}