Given A binary search tree (BST), and find the lowest common ancestor (LCA) of two Given, the BST.
According to the definition of LCA in Wikipedia: "The lowest common ancestor is defined between the two nodes V and W as the L Owest node in T so 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 the nodes 2 and 4 are 2, since a node can be a descendant of itself of the LCA definition.
This topic is relatively simple, directly on the code:
public class Solution {public TreeNode lowestcommonancestor (TreeNode root, TreeNode p, Treen
Ode q) {if (p.val==q.val) return p;
if (P.val>q.val) return Lowestcommonancestor (ROOT,Q,P); if (root.val==p.val| | root.val==q.val| |
(Root.val>p.val&&root.val<q.val))
return root;
if (Root.val<p.val) return Lowestcommonancestor (ROOT.RIGHT,P,Q);
else return Lowestcommonancestor (ROOT.LEFT,P,Q); }
}