private TreeNode ans = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
recurseTreeNode(root, p, q);
return ans;
}
private boolean recurseTreeNode(TreeNode current, TreeNode p, TreeNode q) {
if (current == null) {
return false;
}
int left = recurseTreeNode(current.left, p, q) ? 1 : 0;
int right = recurseTreeNode(current.right, p, q) ? 1: 0;
int mid = (current == p || current == q) ? 1 : 0;
int sum = left + right + mid;
if (sum >= 2) {
ans = current;
}
return sum > 0;
}
网友评论