二叉树的最近公共祖先

一般的二叉树:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
}

  

二叉搜索树:

1
2
3
4
5
6
7
8
9
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 @   ☞@_@  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示