java - What is the best approach? Binary Search Tree : Lowest Common Ancestor using only if statements -
i have solved problem if statements. can solved in various other ways. have started programming, not think of using other data structure solving this.
my question :
how choose best approach among various ways? , advantages/disadvantages of best approach compared direct naive approach.
not problem, in general. how arrive @ possible approach problem?
problem statement
you given pointer root of binary search tree , 2 values v1 , v2. need return lowest common ancestor (lca) of v1 , v2 in binary search tree. need complete function.
my code:
static node lca(node root,int v1,int v2) { node r = root; if( r == null){ return null; } else if(r.data == v1 || r.data == v2){ return r; } else if(r.data > v1 && r.data < v2){ return r; } else if(r.data > v2 && r.data < v1){ return r; } else if( r.data > v1 && r.data > v2){ lca(r.left, v1, v2); } else if( r.data < v1 && r.data < v2){ lca(r.right, v1, v2); } return null; }
problem link: https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor
well, here's how approach problem. relies on fact you're dealing binary search tree.
for given node, can lca if , if min(v1, v2)
in left subtree, , max(v1, v2)
in right subtree. if isn't true, current node can't ancestor, because either v1 or v2 cannot descendant. continue traversing down tree until lca condition met.
your solution correct , have intuition down, can strip out recursion , perform iterative bst find, implicitly contains if
checks.
in terms of advantages, you're wasting implicit recursion call stack space, of has unwind @ end. both of our implementations run in o(log n)
, since you'll examine log n - 1
nodes in worst case, v1
, v2
direct siblings @ bottom of full , complete tree.
implementation
swap
v1
,v2
ifv1 < v2
(remove needmin
,max
checks). implicitly contains both ofif
checksv1 < root < v2
,v2 < root < v1
.while current node's value smaller
v1
(v1
in right subtree) or greaterv2
, move towardsv1
orv2
. replaces recursive traversal.
here's quick implementation checked:
static node lca(node root, int v1, int v2) { if (root == null) return null; if (v1 > v2) { int temp = v2; v2 = v1; v1 = temp; } while (root.data < v1 || root.data > v2) { if (root.data < v1) root = root.right; else if (root.data > v2) root = root.left; } return root; }
Comments
Post a Comment