-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
70 lines (55 loc) · 1009 Bytes
/
main.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
62
63
64
65
66
67
68
69
70
package main
func main() {
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func lcaDeepestLeaves(root *TreeNode) *TreeNode {
p, q := bfs(root)
// fmt.Println(p, q)
return lca(root, p, q)
}
func lca(root, p, q *TreeNode) *TreeNode {
if root == nil {
return nil
}
if root == p || root == q {
return root
}
left := lca(root.Left, p, q)
right := lca(root.Right, p, q)
if left != nil && right != nil {
return root
}
if right != nil {
return right
}
return left
}
func bfs(root *TreeNode) (*TreeNode, *TreeNode) {
q := []*TreeNode{root}
var result []*TreeNode
for len(q) != 0 {
size := len(q)
for i := 0; i < size; i++ {
n := q[0]
result = append(result, n)
q = q[1:]
if n.Left != nil {
q = append(q, n.Left)
}
if n.Right != nil {
q = append(q, n.Right)
}
}
if len(q) != 0 {
result = make([]*TreeNode, 0)
}
}
if len(result) == 1 {
return result[0], result[0]
}
return result[0], result[len(result)-1]
}