236. 二叉树的最近公共祖先
236. 二叉树的最近公共祖先
题解
思路:要找最近的公共祖先,直接递归左右子树,直到左右子树都有的时候,就是答案了
代码
package main
func main() {
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil {
return nil
}
if root == p {
return root
}
if 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
}
if right != nil {
return right
}
return nil
}