题目:
题解:
自顶向下遍历,如果p,q在左树,就在左树中寻找,如果p,q在右树,就在右树中寻找,直到不满足为止,当前根结点就是最近公共祖先,时间复杂度:O(n)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
TreeNode temp = root;
while (true) {
if (temp.val > p.val && temp.val > q.val) {
temp = temp.left;
} else if (temp.val < p.val && temp.val < q.val) {
temp = temp.right;
} else {
return temp;
}
}
}