File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n)
2+ // Space Complexity: O(1)
3+
4+ var lowestCommonAncestor = function ( root , p , q ) {
5+ // start from the root.
6+ let current = root ;
7+
8+ // traverse the tree.
9+ while ( current !== null ) {
10+ // if both p and q are greater than current node, LCA lies in the right.
11+ if ( p . val > current . val && q . val > current . val ) {
12+ current = current . right ;
13+ }
14+ // if both p and q are smaller than current node, LCA lies in the left.
15+ else if ( p . val < current . val && q . val < current . val ) {
16+ current = current . left ;
17+ }
18+ // if one of p or q is on one side and the other is on the other side, It's LCA.
19+ else {
20+ return current ;
21+ }
22+ }
23+
24+ // if the tree is empty.
25+ return null ;
26+ } ;
You can’t perform that action at this time.
0 commit comments