[路飞]_LeetCode_199. 二叉树的右视图

210 阅读1分钟

题目

给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例 1:

image.png

输入: [1,2,3,null,5,null,4]
输出: [1,3,4]

来源:力扣(LeetCode)leetcode-cn.com/problems/bi…

解题思路

看图容易理解成取右子树的所有右节点。其实题目意思是要取每一层最右边的节点,那我们通过层遍历取每层最右边的节点就可以了。

代码实现

var rightSideView = function(root) {
    if (!root) return []
    
    const ans = []
    const queue = [root]

    //层遍历
    while(queue.length) {
        const len = queue.length
        for (let i = 0; i< len; i++) {
            const node = queue.shift()
            if (node.left) queue.push(node.left)
            if (node.right) queue.push(node.right)

            //取当前层最右边的节点
            if (i === len - 1) {
                ans.push(node.val)
            }
        }
    }

    return ans
};

如有错误欢迎指出,欢迎一起讨论!