二叉树的最近公共祖先

一般的二叉树:

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
    }
}

  

posted @ 2022-09-15 14:38  ☞@_@  阅读(18)  评论(0编辑  收藏  举报