Lowest Common Ancestor of a Binary Search Tree
Last updated
Was this helpful?
Last updated
Was this helpful?
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allowa node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes2
and8
is6
. Another example is LCA of nodes2
and4
is2
, since a node can be a descendant of itself according to the LCA definition.
二叉搜索树的特点是左<根<右,所以根节点的值一直都是中间值,大于左子树的所有节点值,小于右子树的所有节点值,那么我们可以做如下的判断,如果根节点的值大于p和q之间的较大值,说明p和q都在左子树中,那么此时我们就进入根节点的左子节点继续递归,如果根节点小于p和q之间的较小值,说明p和q都在右子树中,那么此时我们就进入根节点的右子节点继续递归,如果都不是,则说明当前根节点就是最小共同父节点,直接返回即可
递代
用个while循环来代替递归调用即可,然后不停的更新当前的根节点,也能实现同样的效果:
while的终止条件就是:root大于p,q的值或者都小于p,q的值,也就是他们的差都大于0或者都小于0(不等于0,如果等于0还是返回root)。如果root的值介于p,q之间或者等于其中一个值则停止循环。