GeeksforGeeks » Interview Questions

interview question about BST

(3 posts)

Tags:

  1. sunny
    guest
    Posted 1 year ago #

    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.

  2. Purav
    Member
    Posted 1 year ago #

    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?

  3. HackAlgo
    guest
    Posted 1 year ago #

    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 problem

    But I am using O(n) extra space here


Reply

You must log in to post.

RSS feed for this topic