我已经编写了这个解决方案来查找二叉树的 LCA。它给出了更大输入的时间限制。有人可以指出这段代码中的一个问题。这个问题来自 Leetcode OJ。
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){
return null;
}if((p.val == root.val) || (q.val == root.val)){
return root;
}
if(root.left == null && root.right == null){
return null;
}
boolean leftChildP = isLeftChild(root,p);
boolean leftChildQ = isLeftChild(root,q);
if(isRightChild(root,p) && isLeftChild(root,q)){
return root;
}if(isRightChild(root,q) && isLeftChild(root,p)){
return root;
}
if(leftChildP && leftChildQ){
return lowestCommonAncestor(root.left,p,q);
}
return lowestCommonAncestor(root.right,p,q);}
private boolean isLeftChild(TreeNode root, TreeNode node){
return isChild(root.left,node);
}
private boolean isRightChild(TreeNode root, TreeNode node){
return isChild(root.right,node);
}
private boolean isChild(TreeNode parent, TreeNode child){
if(parent == null){
return false;}
if(parent.val == child.val){
return true;
}return (isChild(parent.left,child) || isChild(parent.right,child));
}}