mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #146 from QuinnDK/添加0236二叉树的最近公共祖先
添加0236二叉树的最近公共祖先 Go版本
This commit is contained in:
@ -266,7 +266,34 @@ Python:
|
||||
|
||||
|
||||
Go:
|
||||
```Go
|
||||
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||
// check
|
||||
if root == nil {
|
||||
return root
|
||||
}
|
||||
// 相等 直接返回root节点即可
|
||||
if root == p || root == q {
|
||||
return root
|
||||
}
|
||||
// Divide
|
||||
left := lowestCommonAncestor(root.Left, p, q)
|
||||
right := lowestCommonAncestor(root.Right, p, q)
|
||||
|
||||
// Conquer
|
||||
// 左右两边都不为空,则根节点为祖先
|
||||
if left != nil && right != nil {
|
||||
return root
|
||||
}
|
||||
if left != nil {
|
||||
return left
|
||||
}
|
||||
if right != nil {
|
||||
return right
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user