Skip to content

LeetCode 199. 二叉树的右视图

作者:Choi Yang
更新于:5 个月前
字数统计:376 字
阅读时长:1 分钟
阅读量:

题目描述

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

示例:

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

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-right-side-view 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

DFS,每一层只能取一个元素,那么我们搜的时候优先考虑右孩子即可。

参考 shetia 大佬图解

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function (root) {
  if (!root) return [];
  let res = [];
  let dfs = (step, root) => {
    if (res.length === step) {
      res.push(root.val);
    }
    // 优先遍历右孩子,再遍历左孩子
    root.right && dfs(step + 1, root.right);
    root.left && dfs(step + 1, root.left);
  };
  dfs(0, root);
  return res;
};

解法二

BFS,对于每一层取队列中对首元素,然后放入队列的时候,如果有对应左右孩子的话,优先放右孩子,再放左孩子。

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var rightSideView = function (root) {
  if (!root) return [];
  let queue = [root];
  let res = [];
  while (queue.length) {
    let size = queue.length;
    res.push(queue[0].val);
    while (size--) {
      let node = queue.shift();
      // 优先放右孩子
      node.right && queue.push(node.right);
      node.left && queue.push(node.left);
    }
  }
  return res;
};
javascript
学如逆水行舟,不进则退

Contributors

Choi Yang