235 Lowest Common Ancestor of a BST
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to thedefinition of LCA on Wikipedia: “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.
这题,因为是个BST,所以可以通过两个点的值的大小来确定LCA。如果是两个root的值在两个点中间,证明那个是LCA,因为在从上往下找。如果两个值都大于根的值,证明两个点都在右子树,同理,如果小于,两个点都在左子树。递归向下求解即可。
非递归版:
Last updated