给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
思路:(刚开始使用boolean来判断要查找的两节点在左右孩子上,后面修改为使用TreeNode与null判断两节点位置)
1、分别向左孩子和右孩子递归。
2、若当前节点等于要查找的两节点之一则返回当前节点。
3、若左孩子和右孩子均不为null,则为公共祖先节点返回。
4、若左孩子不为null,右孩子为null,则查找的两节点以及其公共节点在左孩子上,返回左孩子。
5、若右孩子不为null,左孩子为null,则查找的两节点以及其公共节点在右孩子上,返回右孩子。
6、其他情况均返回null。
class Solution {
//public TreeNode t=null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return lowestCommon(root,p,q);
}
/*通过返回true或false判断寻找的点在哪条分支,其实也可以直接返回所在分支的根节点,见下面未标为备注的思路
public boolean lowestCommon(TreeNode root, TreeNode p, TreeNode q){
if(root==null){return false;}
boolean left = lowestCommon(root.left,p,q);
boolean right = lowestCommon(root.right,p,q);
boolean current = false;
if(root.val==p.val||root.val==q.val){
current=true;
}
if(left&&right&&!current||left&¤t&&!right||right&¤t&&!left){t=root;}
return left||right||current;
}*/
public TreeNode lowestCommon(TreeNode root, TreeNode p, TreeNode q){
if(root==null){return root;}
TreeNode left = lowestCommon(root.left,p,q);
TreeNode right = lowestCommon(root.right,p,q);
if(root.val==p.val||root.val==q.val){
return root;
}
if(left!=null&&right!=null){
return root;
}
if(left!=null){
return left;
}
if(right!=null){
return right;
}
return null;
}
}