题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)”
条件
- p != q
- p 和 q 均存在于给定的二叉树中。
示例
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出:5
解释:节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。
解题思路
第一步:写出遍历二叉树的模板:
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(eoot.right,p.q);
第二步:写出base case
if(root==null){
return null;
}
if(root==p||root==q){
return root;
}
- 分情况进行套路
1、如果p在root的左子树,q在root的右子树,那么根据base case可以知道left不为空,right也不为空,就可以知道p和q的最近公共祖先就是根节点
2、如果p和q同时在root的左子树,那么根据base case可以知道left不为空,right为空,这种情况p和q的最近公共祖先就是left
3、如果p和q同时在root的右子树,那么根据base case可以知道right不为空,left为空,这种情况p和q的最近公共祖先就是left
AC 代码
/**
* 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){
return null;
}
if(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 root;
}
if(left!=null&&right==null){
return left;
}
if(left==null&&right!=null){
return right;
}
return null;
}
}
总结
发现自己总结下来一波,这道算法题,我已经可以独立写出来了,开心。写树的这类题目,最重要的是要利用分治的实现,同时要理解函数的意义是什么,比如说这道题目的函数是返回最小的公共祖先,其实要写出base case,最后再分情况讨论,像二叉树的左右子树组合一下一般就是三种情况