算法学习记录(八十六)

109 阅读1分钟

199. 二叉树的右视图

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

image.png

解:

二叉树递归套路,返回的信息为当前节点值左子树的沿途节点值数组右子树沿途节点值数组合并(当左子树数组比右子树数组更长时,就把多出来的那一截保留,拼接到要返回的信息中)的结果。 当获得到左右子树信息后处理完毕加工出当前节点信息返回。

const rightSideView = function(root) {
    function getRes (node) {
        if (!node) return [] 
        const leftInfo = getRes(node.left)
        const rightInfo = getRes(node.right)
        const curInfo = [node.val]
        // 左子树比右子树长时,多出来的那一截数组,这就是当右树长度不够时,右视图会看到的左树的部分
        let needVal = []
        if (leftInfo.length > rightInfo.length) {
            needVal = leftInfo.slice(rightInfo.length)
        }
        curInfo.push(...rightInfo, ...needVal)
        return curInfo
    }
    return getRes(root)
};