Given a binary search tree T, where each node contains a positive integer, and an integer K, you have to find whether or not there exist two different nodes A and B such that A.value + B.value = K.
Return 1 to denote that two such nodes exist. Return 0, otherwise.
Notes
Your solution should run in linear time and not take memory more than O(height of T).
Assume all values in BST are distinct.
Example :
Input 1:
T : 10
/ \
9 20
K = 19
Return: 1
Input 2:
T: 10
/ \
9 20
K = 40
Return: 0
Method:
Treat BST as a sorted array, and use two pointer by using two interators
Solution:
Time: O(n) Space: O(height of T)
/** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public int t2Sum(TreeNode A, int B) { Deque<TreeNode> stack = new ArrayDeque<>(); Deque<TreeNode> rStack = new ArrayDeque<>(); TreeNode curr = A; TreeNode rCurr = A; while (curr != null || rCurr != null || !stack.isEmpty() || !rStack.isEmpty()) { while (curr != null) { stack.push(curr); curr = curr.left; } while (rCurr != null) { rStack.push(rCurr); rCurr = rCurr.right; } if (!stack.isEmpty() && !rStack.isEmpty()) { curr = stack.pop(); rCurr = rStack.pop(); // System.out.println("l: " + curr.val + ", r: " + rCurr.val); if (curr == rCurr) return 0; int sum = curr.val + rCurr.val; if (sum == B) { return 1; } else if (sum < B) { curr = curr.right; rStack.push(rCurr); rCurr = null; } else { rCurr = rCurr.left; stack.push(curr); curr = null; } } } return 0; } }