You are viewing a single comment's thread. Return to all comments →
From my HackerRank solutions.
Make sure to leverage the fact that this is a binary search tree. We assume the tree has unique values.
Runtime: O(log n) on a balanced tree Space Complexity: O(1)
I solve it iteratively since recursion would take O(log n) space complexity
static Node lca(Node n, int v1, int v2) { while (n != null) { if (n.data > v1 && n.data > v2) { n = n.left; } else if (n.data < v1 && n.data < v2) { n = n.right; } else { break; } } return n; }
Let me know if you have any questions.
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Search Tree : Lowest Common Ancestor
You are viewing a single comment's thread. Return to all comments →
Efficient Java solution - passes 100% of test cases
From my HackerRank solutions.
Make sure to leverage the fact that this is a binary search tree. We assume the tree has unique values.
Runtime: O(log n) on a balanced tree
Space Complexity: O(1)
I solve it iteratively since recursion would take O(log n) space complexity
Let me know if you have any questions.