二叉树的最近公共祖先
一般的二叉树:
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root==p||root==q||root==nil{
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 right
}
return left
}
二叉搜索树:
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root.Val>p.Val&&root.Val>q.Val{
return lowestCommonAncestor(root.Left,p,q)
}else if root.Val<p.Val&&root.Val<q.Val{
return lowestCommonAncestor(root.Right,p,q)
}else{
return root
}
}

浙公网安备 33010602011771号