Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition 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 allow a node to be a descendant of itself).”
_______6______ / ___2__ ___8__ / / 0 _4 7 9 / 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
思路:找A与B的LCA,有两种可能 1. A或B是另一个点得祖先。比如3,2的LCA就是2。
2. 一个TreeNode,它的左右子树一个包含A,一个包含B。
这种思路是对于binary tree与binary search tree都适用的,还有一种方法,利用了BST得特点,通过对数值的运算确定了,这个LCA是在root的左子树还是右子树,还是root本身。在leetcode的disscusion中有人提到了。两种的代码如下:
1 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){ 2 if (root == null || root == p || root == q) { 3 return root; 4 } 5 TreeNode left = lowestCommonAncestor(root.left, p, q); 6 TreeNode right = lowestCommonAncestor(root.right, p, q); 7 8 if (left != null && right != null) { 9 return root; 10 } 11 if (left != null) { 12 return left; 13 } 14 if (right != null) { 15 return right; 16 } 17 return null; 18 }
1 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 2 while((root.val - p.val) * (root.val - q.val) > 0) { 3 root = (root.val - p.val) > 0 ? root.left : root.right; 4 } 5 return root; 6 }