二叉树的最近公共祖先【二叉树】-爱代码爱编程
题目
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
出现公共祖先的情况:
- 节点A的左孩子是B,右孩子是C,那么A就是B和C的最近公共祖先。
- 节点B的左孩子是C,那么节点B就是B和C的最近公共祖先。
- 节点B的右孩子是C,那么节点B就是B和C的最近公共祖先。
用什么方法,可以找到某节点的做孩子,右孩子,还能返回该节点呢?当找到一个节点的左孩子是p(q),右孩子是q§,那就返回这个节点就好了。如果是第二和三的情况,找到p或q其中一个,返回的节点也就是最小公共祖先了。
代码要遍历整棵树,因为要对返回值做判断。比如:
- 递归遍历左子树为p,递归遍历右子树为q,那说明最小公共祖先就是根节点了。
- 递归遍历左子树为空,那最小公共祖先就是递归遍历右子树的返回值。
代码
/**
* 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) {
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 && right != null) {
return right;
} else if(left != null && right == null) {
return left;
} else if(left == null && right == null){
return null;
} else {
return root;
}
}
}