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
| /**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
result, _, _ := find(root, p, q)
return result
}
func find(root, p, q *TreeNode) (*TreeNode, bool, bool) {
var hasP, hasQ bool
switch root {
case p:
hasP = true
case q:
hasQ = true
case nil:
return nil, hasP, hasQ
}
left := root.Left
result, lHasP, lHasQ := find(left, p, q)
if lHasP && lHasQ {
return result, lHasP, lHasQ
}
right := root.Right
result, rHasP, rHasQ := find(right, p, q)
if rHasP && rHasQ {
return result, rHasP, rHasQ
}
return root, hasP || lHasP || rHasP, hasQ || lHasQ || rHasQ
}
|