题目:
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
算法:
思路:dfs遍历node时返回两个参数p,q是否存在node的子节点下
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
var dfs func(node, p, q *TreeNode) (bool, bool)
var ans *TreeNode
dfs = func(node, p, q *TreeNode) (bool, bool) {
if node == nil {
return false, false
}
pInLeft, qInLeft := dfs(node.Left, p, q)
pInRight, qInRight := dfs(node.Right, p, q)
if (pInLeft || pInRight) && (qInLeft || qInRight) && ans == nil {
ans = node
}
if p.Val == node.Val {
if qInLeft || qInRight && ans == nil{
ans = node
}
return true, false
}
if q.Val == node.Val {
if pInLeft || pInRight && ans == nil{
ans = node
}
return false, true
}
return pInLeft || pInRight, qInLeft || qInRight
}
dfs(root, p, q)
return ans
}