Find the Closest Element in BST

https://practice.geeksforgeeks.org/problems/find-the-closest-element-in-bst/1/

Input:
        10
      /   \
     2    11
   /  \ 
  1    5
      /  \
     3    6
      \
       4
K = 13
Output: 2
Explanation: K=13. The node that has
value nearest to K is 11. so the answer
is 2

class Solution
{
public:
    void helper(Node *root, int &mn_dif, int &k)
    {
        if (root = NULL)
            return;
        mn_dif = min(mn_dif, abs(root->data - k));
        if (root->data > k)
            helper(root->left, mn_dif, k);
        else if (root->data < k)
            helper(root->right, mn_dif, k);
        else
            return;
    }
    int minDiff(Node *root, int K)
    {
        int mn_dif = INT_MAX;
        helper(root, mn_dif, K);
        return mn_dif;
    }
};

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree