Find two elements in balanced BST which sums to a given a value. Constraints Time O(n) and space O(log n).
The Brute Force Solution is to consider each pair in BST and check whether the sum equals to X. The time complexity of this solution will be O(n^2).
A Better Solution is to create an auxiliary array and store Inorder traversal of BST in the array. The array will be sorted as Inorder traversal of BST always produces sorted data. Once we have the Inorder traversal, we can pair in O(n) time. This solution works in O(n) time, but requires O(n) auxiliary space.
The idea is same as finding the pair in sorted array. We traverse BST in Normal Inorder and Reverse Inorder simultaneously. In reverse inorder, we start from the rightmost node which is the maximum value node. In normal inorder, we start from the left most node which is minimum value node. We add sum of current nodes in both traversals and compare this sum with given target sum. If the sum is same as target sum, we return true. If the sum is more than target sum, we move to next node in reverse inorder traversal, otherwise we move to next node in normal inorder traversal. If any of the traversals is finished without finding a pair, we return false. Following is C++ implementation of this approach.
public static int[] findSum(int toSearch, Node root){
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
Node cur1 = root;
Node cur2 = root;
boolean done1 = false, done2 = false;
int val1 = 0, val2 = 0;
while (true) {
while(!done1){
if(cur1 != null){
s1.push(cur1);
cur1 = cur1.left;
}
else {
if(s1.isEmpty()) done1 = true;
else {
cur1 = s1.pop();
val1 = cur1.value;
cur1 = cur1.right;
done1 = true;
}
}
}
while(!done2){
if(cur2 != null){
s2.push(cur2);
cur2 = cur2.right;
}
else {
if(s2.isEmpty()) done2 = true;
else {
cur2 = s2.pop();
val2 = cur2.value;
cur2 = cur2.left;
done2 = true;
}
}
}
if (val1 + val2 == toSearch){
int[] res = {val1,val2};
return res;
}
else if (val1 + val2 > toSearch){
done2 = false;
}
else {
done1 = false;
}
}
}
No comments:
Post a Comment