美文网首页
二叉树的最近公共祖先

二叉树的最近公共祖先

作者: momdiemg | 来源:发表于2020-03-03 14:26 被阅读0次
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==p||root==q||root==null){
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null&&right!=null){
          return root;
        }
        if(left==null){
            return right;
        }else{
            return left;
        }
    }
}


相关文章

网友评论

      本文标题:二叉树的最近公共祖先

      本文链接:https://www.haomeiwen.com/subject/lboclhtx.html