Back to articles
Two Sum IV – Input is a BST (Two Pointer Approach)

Two Sum IV – Input is a BST (Two Pointer Approach)

via Dev.toNithya Dharshini official

We already know the classic Two Sum problem on arrays. But what if the data is inside a Binary Search Tree (BST)? At first, it looks tricky… but we can convert it into something familiar. Key Idea A BST inorder traversal gives a sorted array.Once we have a sorted array, we can apply: -> Two Pointer Technique Approach Step 1: Convert BST → Sorted Array Use inorder traversal Left → Root → Right This guarantees sorted order. Step 2: Apply Two Pointers left = 0 , right = n - 1 Then: If sum == target -> return true If sum < target -> move left++ If sum > target -> move right-- Why This Works BST property -> inorder gives sorted values Sorted values -> perfect for two pointer optimization So we reduce: Tree problem -> Array problem Code (C++) class Solution { public: void inorder ( TreeNode * root , vector < int >& arr ) { if ( root == NULL ) return ; inorder ( root -> left , arr ); arr . push_back ( root -> val ); inorder ( root -> right , arr ); } bool findTarget ( TreeNode * root , int k

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles