「每日LeetCode」2022年6月22日

本文最后更新于:2023年3月19日 晚上

513.找树左下角的值

513.找树左下角的值

Category Difficulty Likes Dislikes
algorithms Medium (73.14%) 317 -

Tags
Companies
给定一个二叉树的 根节点 root,请找出该二叉树的 **最底层 最左边 **节点的值。
假设二叉树中至少有一个节点。

示例 1:

输入: **root = [2,1,3] **输出: **1
**示例 2:


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

提示:

  • 二叉树的节点个数的范围是 [1,104]
  • -231 <= Node.val <= 231 - 1

Discussion | Solution

思路

采用先序遍历,当深度更新时的第一个节点就是最左下角的值。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
* @lc app=leetcode.cn id=513 lang=javascript
*
* [513] 找树左下角的值
*/

// @lc code=start
/**
* 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 findBottomLeftValue = function (root) {
let depth = 0,
max = -Infinity,
res;
const visit = (node) => {
if (!node) return;
depth++;
if (depth > max) {
res = node.val;
max = depth;
}
visit(node.left);
visit(node.right);
depth--;
};
visit(root);
return res;
};
// @lc code=end