45.二叉树的右视图

88 阅读1分钟

题目链接

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

解法1 层序遍历bfs

思路

右视图其实就是每一层的最后一个节点,这样我们可以通过层序遍历的方法,先把二叉树遍历出来形成一个二维数组。

而这个二维数组的每一维的最后一个数就是这个颗数的右视图。

代码

function rightSideView(root: TreeNode | null): number[] {
    const nodeList = [];
    if (!root) return nodeList;
    const queue = [root];

    while (queue.length) {
        const size = queue.length;
        const level = [];
        for (let i = 0; i < size; i++) {
            const node = queue.shift();
            level.push(node.val);
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
        nodeList.push(level);
    }

    return nodeList.map(i => i[i.length - 1]);
};

时空复杂度

时间复杂度:O(n)

空间复杂度:O(n)

解法2 递归dfs

思路

如果使用 dfs 则需要记录它的深度,可以直接从右子树开始遍历,第一次到达新深度就记录这个值,说明这是右视的第一个节点。

代码

function rightSideView(root: TreeNode | null): number[] {
    const result = [];

    const dfs = (node, depth) => {
        if (!node) return;

        if (depth === result.length) {
            result.push(node.val);
        }

        dfs(node.right, depth + 1);
        dfs(node.left, depth + 1);
    }

    dfs(root, 0);
    return result;
};

时空复杂度

时间复杂度:O(n)

空间复杂度:O(h),最差 O(n),最优是 O(logn)