Day 1.31
二叉树的最近公共祖先
题目
思路(1)
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(right(root,p)&&right(root,q))root=root.right;
while(left(root,p)&&left(root,q))root=root.left;
return root;
}
public boolean left(TreeNode root,TreeNode t){
if(root.left==null)return false;
if((root.left==t)||(left(root.left,t)||right(root.left,t))){
return true;
}
return false;
}
public boolean right(TreeNode root,TreeNode t){
if(root.right==null)return false;
if((root.right==t)||(left(root.right,t)||right(root.right,t))){
return true;
}
return false;
}
}
思路(2)(答案)
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)return right;
if (right == null)return left;
return root;
}
}