72、二叉树的最近公共祖先

题目描述:
在这里插入图片描述
在这里插入图片描述
LCA(LCA最近公共祖先)问题,和之前那个的二叉搜索树的最近公共祖先区别是这是普通的二叉树
注意p,q必然存在树内, 且所有节点的值唯一!!!
递归思想, 对以root为根的(子)树进行查找p和q, 如果root == null || p || q 直接返回root
表示对于当前树的查找已经完毕, 否则对左右子树进行查找, 根据左右子树的返回值判断:
1. 左右子树的返回值都不为null, 由于值唯一左右子树的返回值就是p和q, 此时root为LCA
2. 如果左右子树返回值只有一个不为null, 说明只有p和q存在与左或右子树中, 最先找到的那个节点为LCA
3. 左右子树返回值均为null, p和q均不在树中, 返回null

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  if(p == root || q == root){
			return root;
		}
		if(root == null)
			return null;
		TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        
        return left == null ? right:right == null? left : root;      
    }
}

最后的那个是三目运算符,表示的是如果left等于null则返回right,如果right等于null则返回left,如果二者都不为null那么返回root。

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/89197937