GeeksforGeeks » Interview Questions
interview question about BST
(3 posts)-
You are given a binary search tree and a number k. Write an algorithm that that gives all pairs of nodes p and q in the tree such that p+q=k.
-
let n = no of elements in BST.
for each element p in the BST, u calculate q = k - p.
if q != p, search if element q exists in the BST( in log(n) time ).
if q exists in the BST, then print p and q.
Total complexity is n * log(n)Anyone with a better approach?
-
Actually its not n * logn , in worst case it can be n^2 since it is bst not a balanced binary search tree , worst bst can be just a path like tree ,
in that case ur method takes n^2 ,Fastest I see is that traverse the tree inOrder , save it an array (which is actually sorted )
and then use O(n) double pointers one at first and one at end .increasing and decreasing steadily standard approach on the array approach to solve the problemBut I am using O(n) extra space here
Reply
You must log in to post.