添加新题目
This commit is contained in:
29
二叉树/二叉树的最近公共祖先/main.go
Normal file
29
二叉树/二叉树的最近公共祖先/main.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
}
|
||||
|
||||
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 && right != nil {
|
||||
return root
|
||||
}
|
||||
if left != nil {
|
||||
return left
|
||||
}
|
||||
return right
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user