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
| // @Title: 二叉树的最近公共祖先 (二叉树的最近公共祖先 LCOF)
// @Author: 15816537946@163.com
// @Date: 2022-02-20 23:57:59
// @Runtime: 4 ms
// @Memory: 7.4 MB
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
left := lowestCommonAncestor(root.Left,p,q)
right := lowestCommonAncestor(root.Right,p,q)
if left == nil {
return right
}
if right == nil {
return left
}
return root
}
|