-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path513. Find Bottom Left Tree Value.go
61 lines (55 loc) · 1.2 KB
/
513. Find Bottom Left Tree Value.go
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 DFS
func findBottomLeftValue(root *TreeNode) int {
if root == nil {
return 0
}
res, maxHeight := 0, -1
findBottomLeftValueDFS(root, 0, &res, &maxHeight)
return res
}
func findBottomLeftValueDFS(root *TreeNode, curHeight int, res, maxHeight *int) {
if curHeight > *maxHeight && root.Left == nil && root.Right == nil {
*maxHeight = curHeight
*res = root.Val
}
if root.Left != nil {
findBottomLeftValueDFS(root.Left, curHeight+1, res, maxHeight)
}
if root.Right != nil {
findBottomLeftValueDFS(root.Right, curHeight+1, res, maxHeight)
}
}
// 解法二 BFS
func findBottomLeftValue1(root *TreeNode) int {
queue := []*TreeNode{root}
for len(queue) > 0 {
next := []*TreeNode{}
for _, node := range queue {
if node.Left != nil {
next = append(next, node.Left)
}
if node.Right != nil {
next = append(next, node.Right)
}
}
if len(next) == 0 {
return queue[0].Val
}
queue = next
}
return 0
}