🧠
Inorder Traversal + Two Pointer
💡 This approach uses the BST's sorted property explicitly by converting it to a sorted array and then applying the classic two-pointer technique to find the target sum efficiently.
Intuition
Perform an inorder traversal to get a sorted list, then use two pointers at the start and end to find if any pair sums to k.
Algorithm
- Perform an inorder traversal of the BST to get a sorted list of node values.
- Initialize two pointers: left at start, right at end of the list.
- While left < right, check sum of values at pointers.
- If sum equals k, return true; if sum < k, move left pointer right; else move right pointer left.
- If pointers cross without finding sum, return false.
💡 This approach is efficient and easy to implement once you understand inorder traversal and two-pointer technique.
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder(root: Optional[TreeNode], arr: List[int]) -> None:
if root is None:
return
inorder(root.left, arr)
arr.append(root.val)
inorder(root.right, arr)
def findTarget(root: Optional[TreeNode], k: int) -> bool:
arr = []
inorder(root, arr)
left, right = 0, len(arr) - 1
while left < right:
s = arr[left] + arr[right]
if s == k:
return True
elif s < k:
left += 1
else:
right -= 1
return False
# Example usage:
# root = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(6, None, TreeNode(7)))
# print(findTarget(root, 9)) # Output: True
Line Notes
def inorder(root: Optional[TreeNode], arr: List[int]) -> None:Helper to collect BST values in sorted order
arr.append(root.val)Add current node's value to sorted list
left, right = 0, len(arr) - 1Initialize two pointers at array ends
while left < right:Loop until pointers cross
s = arr[left] + arr[right]Calculate sum of current pair
if s == k:Check if sum matches target
elif s < k:If sum too small, move left pointer right
else:If sum too large, move right pointer left
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class Solution {
public void inorder(TreeNode root, List<Integer> arr) {
if (root == null) return;
inorder(root.left, arr);
arr.add(root.val);
inorder(root.right, arr);
}
public boolean findTarget(TreeNode root, int k) {
List<Integer> arr = new ArrayList<>();
inorder(root, arr);
int left = 0, right = arr.size() - 1;
while (left < right) {
int sum = arr.get(left) + arr.get(right);
if (sum == k) return true;
else if (sum < k) left++;
else right--;
}
return false;
}
// Example main
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(6);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.right = new TreeNode(7);
Solution sol = new Solution();
System.out.println(sol.findTarget(root, 9)); // true
}
}
Line Notes
public void inorder(TreeNode root, List<Integer> arr)Helper to collect BST values in sorted order
arr.add(root.val);Add current node's value to list
int left = 0, right = arr.size() - 1;Initialize two pointers at array ends
while (left < right) {Loop until pointers cross
int sum = arr.get(left) + arr.get(right);Calculate sum of current pair
if (sum == k) return true;Check if sum matches target
else if (sum < k) left++;If sum too small, move left pointer right
else right--;If sum too large, move right pointer left
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void inorder(TreeNode* root, vector<int>& arr) {
if (!root) return;
inorder(root->left, arr);
arr.push_back(root->val);
inorder(root->right, arr);
}
bool findTarget(TreeNode* root, int k) {
vector<int> arr;
inorder(root, arr);
int left = 0, right = (int)arr.size() - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == k) return true;
else if (sum < k) left++;
else right--;
}
return false;
}
// Example usage
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(6);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->right = new TreeNode(7);
cout << (findTarget(root, 9) ? "true" : "false") << endl; // true
return 0;
}
Line Notes
void inorder(TreeNode* root, vector<int>& arr)Helper to collect BST values in sorted order
arr.push_back(root->val);Add current node's value to vector
int left = 0, right = (int)arr.size() - 1;Initialize two pointers at array ends
while (left < right) {Loop until pointers cross
int sum = arr[left] + arr[right];Calculate sum of current pair
if (sum == k) return true;Check if sum matches target
else if (sum < k) left++;If sum too small, move left pointer right
else right--;If sum too large, move right pointer left
class TreeNode {
constructor(val=0, left=null, right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function inorder(root, arr) {
if (root === null) return;
inorder(root.left, arr);
arr.push(root.val);
inorder(root.right, arr);
}
function findTarget(root, k) {
const arr = [];
inorder(root, arr);
let left = 0, right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === k) return true;
else if (sum < k) left++;
else right--;
}
return false;
}
// Example usage:
// const root = new TreeNode(5, new TreeNode(3, new TreeNode(2), new TreeNode(4)), new TreeNode(6, null, new TreeNode(7)));
// console.log(findTarget(root, 9)); // true
Line Notes
function inorder(root, arr) {Helper to collect BST values in sorted order
arr.push(root.val);Add current node's value to array
let left = 0, right = arr.length - 1;Initialize two pointers at array ends
while (left < right) {Loop until pointers cross
const sum = arr[left] + arr[right];Calculate sum of current pair
if (sum === k) return true;Check if sum matches target
else if (sum < k) left++;If sum too small, move left pointer right
else right--;If sum too large, move right pointer left
Inorder traversal takes O(n), two-pointer scan takes O(n).
💡 For n=20 nodes, about 40 operations total, very efficient.
Interview Verdict: Accepted
This approach is optimal in time and easy to implement, making it a great choice in interviews.