【前端er每日算法】Leetcode199 二叉树的右视图

61 阅读1分钟

题目199. 二叉树的右视图

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

思路

右视图就是最右侧的节点。

  • 最先想到的就是层次遍历,取最后一个节点即可,这个很容易想出来。
  • 再看了下题解,还可以深度优先遍历右节点,那么每层的第一个节点就是结果,那怎么判断是每层的第一个节点呢,如果数组的大小和层数相同,说明是第一个进入的右节点,放进去,其他就不放了。

解题

// 层次遍历
var rightSideView = function(root) {
    let res = [];
    if (!root) {
        return res;
    }
    const queue = [root];
    while (queue.length) {
        const len = queue.length;
        for (let i = 0; i < len; i++) {
            const node = queue.shift();
            if (i === len - 1) {
                res.push(node.val);
            }
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
    }
    return res;
}
/**
 * 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 = [];
    const getRight = (node, depth) => {
        if (!node) {
            return;
        }
        if (res.length === depth) {
            res.push(node.val);
        }
        if (node.right) {
            getRight(node.right, depth + 1);
        }
        if (node.left) {
            getRight(node.left, depth + 1);
        }
    }
    getRight(root, 0);
    return res;
};