算法-树-二叉树的最近公共祖先

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    
    
        //首先p q肯定是树的节点   所以root肯定不为空
        //这里的root可以是从任意节点来看,root == null就直接返回null  如果root == p或q 说明自己就是祖先 直接返回当前节点
        if(root==null||root==p||root==q)
            return root;
        //返回左子树的公共节点
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        //返回右子树的公共节点
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left==null)
        //左子树的公共节点为空
            return right;
        //右子树的公共节点为空t;
        if(right==null)
            return left;
        //左一个节点  右一个节点 
        return root;//因为是先返回右 后返回左  最后返回根 自底向上  能保证最深
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45100361/article/details/113513912