文章目录
513. 找树左下角的值
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:

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

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
提示:
- 二叉树的节点个数的范围是 [ 1 , 1 0 4 ] [1,10^4] [1,104]
- − 2 31 < = N o d e . v a l < = 2 31 − 1 -2^{31} <= Node.val <= 2^{31} - 1 −231<=Node.val<=231−1
解题思路
可以层序遍历,然后拿到最后一层的第一个元素。
也可以递归遍历,拿到最大深度的第一个元素即可。
Go代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findBottomLeftValue(root *TreeNode) int {
// 采用前中后序遍历都可以,因为只要能保证左节点比右节点先访问就可以啦
// 第一次进入最大深度的就是最底层最左边的节点
if root == nil {
return 0
}
res := 0
maxDepth := math.MinInt32
dfs(root,&res,1,&maxDepth) // 根节点认为是第一层
return res
}
func dfs(root *TreeNode,res *int,depth int,maxDepth *int) {
if root == nil {
return
}
// 深度增加了,肯定是初次遍历到某层时深度比最大深度还大了,此时的节点就是当前层的最左节点
if depth > *maxDepth {
*res = root.Val
*maxDepth = depth
}
if root.Left != nil {
depth++
dfs(root.Left,res,depth,maxDepth)
depth--
// 上面三行是故意这么写的,更清楚的看到回溯过程,实际三行可以写成下面一行
// dfs(root.Left,res,depth+1,maxDepth)
}
if root.Right != nil {
dfs(root.Right,res,depth+1,maxDepth)
}
}

654

被折叠的 条评论
为什么被折叠?



