Skip to content
Related Articles

Related Articles

Find minimum Diameter BST having Sum equal to target K

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 29 Jul, 2022
View Discussion
Improve Article
Save Article

Given a binary tree and a target K, the task is to find the diameter of the minimum subtree having sum equal to K which is also a binary search tree. Return -1 if not possible.

Examples:

Input: K = 38
          13
        /    \
      5       23
     / \      / \
 N  17   N   N
     /   \
  16   N
Output: 3
Explanation: 5, 17, 16 is the smallest subtree with diameter 3.

Input: K = 73
            7
          /   \
       N     23
            /     \
         10      23
        /  \     / \
   N   17   N   N
Output: -1
Explanation: No subtree is BST for the given target.

 

Approach:

This problem can be solved using the idea of Dynamic Programming on Trees. Store the sum and diameter of every subtree and check if a subtree with sum K is also a binary search tree or not.

The following steps can be taken to solve this problem: 

  • Create Hash tables to store the sum of the subtree, diameter of subtree, min value of subtree, and max value of subtree.
  • Initialize the answer as infinity.
  • Now store all values in the hash tables and check if the given binary tree is a BST using Depth-first traversal.
  • During the traversal, only the hash tables will be filled.
  • For a binary to be a BST following 3 conditions must be satisfied:
    • Left and right subtree must be BST.
    • Max value of left subtree < value of the current node
    • Min value of right subtree > value of the current node

Below is the implementation of the above approach:

C++




// C++ code to implement this approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Structure of node of tree
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int num)
    {
        data = num;
        left = NULL;
        right = NULL;
    }
};
int target, ans;
  
// Hash Tables to store Minimum value, Maximum Value,
// diameter of subtree and sum of elements of subtree
unordered_map<Node *, int> minv, maxv, h, sum;
  
// Function to check if the tree is a BST or not
bool isBST(Node* root)
{
    // Base condition
    if (root == NULL)
        return true;
    if (root->left == NULL
        and root->right == NULL) {
        minv[root] = root->data;
        maxv[root] = root->data;
        h[root] = 1;
        sum[root] = root->data;
        if (sum[root] == target)
            ans = min(ans, h[root]);
        return true;
    }
  
    // Condition for Binary tree to be a BST
    if (root->left == NULL) {
        if (isBST(root->right)
            and minv[root->right] > root->data) {
            minv[root] = root->data;
            maxv[root] = maxv[root->right];
            h[root] = h[root->right] + 1;
            sum[root] = sum[root->right] + root->data;
            if (sum[root] == target)
                ans = min(ans, h[root]);
            return true;
        }
        return false;
    }
    if (root->right == NULL) {
        if (isBST(root->left)
            and maxv[root->left] < root->data) {
            minv[root] = minv[root->left];
            maxv[root] = root->data;
            h[root] = h[root->left] + 1;
            sum[root] = sum[root->left] + root->data;
            if (sum[root] == target)
                ans = min(ans, h[root]);
            return true;
        }
        return false;
    }
    bool bstleft = isBST(root->left);
    bool bstright = isBST(root->right);
    if (bstleft and bstright
        and maxv[root->left] < root->data
        and minv[root->right] > root->data) {
        minv[root] = minv[root->left];
        maxv[root] = maxv[root->right];
        h[root] = 1 + h[root->left] + h[root->right];
        sum[root] = root->data + sum[root->left]
                    + sum[root->right];
        if (sum[root] == target)
            ans = min(ans, h[root]);
        return true;
    }
    return false;
}
  
// Function to find the desired subtree
int minSubtreeSumBST(int k, Node* root)
{
    // Initialize answer as infinity(INT_MAX)
    ans = INT_MAX;
    target = k;
  
    // check for BST using DFS traversal
    isBST(root);
    if (ans == INT_MAX)
        return -1;
    return ans;
}
  
// Driver code
int main()
{
    int k = 38;
  
    // Defining tree
    Node* root = new Node(13);
    root->left = new Node(5);
    root->right = new Node(23);
    root->left->right = new Node(17);
    root->left->right->left = new Node(16);
  
    // Function call
    int res = minSubtreeSumBST(k, root);
    cout << res << endl;
    return 0;
}


Output

3

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!