“Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。”
今天写了二叉树的中序遍历,所以打算把热题100中关于二叉树的题,都解一遍,方便大家专项学习
一、题目描述
-
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
二、思路分析
-
这道题还是运用递归的思想来做
-
如果根节点的左子树和右子树都不为空则公共祖先为根节点
-
如果左子树为空则公共节点在右边
-
如果右子树为空则公共节点在左边
三、AC 代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//边界条件,为null直接返回
if(root == null){
return null;
}
// 相等返回根节点
if(root.val == p.val || root.val == q.val){
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;
}
if(right == null){
return left;
}
return null;
}
}
四、总结:
- 好了,代码撸完,我们
总结一下:-
递归调用
-
左子树为空则公共祖先为右子树
-
右子树为空则公共祖先为左子树
-