The Wayback Machine - https://web.archive.org/web/20241010175011/https://www.geeksforgeeks.org/transform-bst-sum-tree/
Open In App

Transform a BST to greater sum tree

Last Updated : 05 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
66.73%
14.4K

Given a BST, transform it into a greater sum tree where each node contains the sum of all nodes greater than that node.

Example:

Input:

Transform-a-BST-to-greater-sum-tree

Output:

Transform-a-BST-to-greater-sum-tree-2


Explanation:  The above tree represents the greater sum tree where each node contains the sum of all nodes greater than that node in original tree.

  • The root node 11 becomes 119 (sum of 15 + 29 + 35 + 40).
  • The left child of 11 becomes 137 (sum of 7 + 11 + 15 + 29 + 35 + 40).
  • The right child of 11 becomes 75 (sum of 35 + 40) and so on.

[Naive Approach] By Calculating Sum for Each Node – O(n^2) Time and O(n) Space

This method doesn’t require the tree to be a BST. Following are the steps:

  • Traverse node by node (in-order, pre-order, etc.).
  • For each node, find all the nodes greater than the current node and sum their values. Store all these sums.
  • Replace each node’s value with its corresponding sum by traversing in the same order as in Step 1.

Below is the implementation of the above approach:

C++
// C++ program to transform a BST to sum tree

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int value) {
        data = value;
        left = nullptr;
        right = nullptr;
    }
};

// Function to find nodes having greater value than current node.
void findGreaterNodes(Node* root, Node* curr, unordered_map<Node*,int> &map) {
    if (root == nullptr) return;
    
    // if value is greater than node, then increment 
    // it in the map
    if (root->data > curr->data) 
        map[curr] += root->data;
        
    findGreaterNodes(root->left, curr, map);
    findGreaterNodes(root->right, curr, map);
}

void transformToGreaterSumTree(Node* curr, Node* root, 
                               unordered_map<Node*,int>&map) {
    if (curr == nullptr) {
        return;
    }

    // Find all nodes greater than current node
    findGreaterNodes(root, curr, map);
    
    // Recursively check for left and right subtree.
    transformToGreaterSumTree(curr->left, root, map);
    transformToGreaterSumTree(curr->right, root, map);
}

// Function to update value of each node.
void preOrderTrav(Node* root, unordered_map<Node*, int> &map) {
    if (root == nullptr) return;
    
    root->data = map[root];
    
    preOrderTrav(root->left, map);
    preOrderTrav(root->right, map);
}

void transformTree(Node* root) {
  
      // map to store greater sum for each node.
      unordered_map<Node*, int> map;
    transformToGreaterSumTree(root, root, map);
    
    // update the value of nodes
    preOrderTrav(root, map);
}

void inorder(Node* root) {
    if (root == nullptr) {
        return;
    }
    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}

int main() {

    // Constructing the BST
    //     11
    //    /  \
    //   2    29
    //  / \   / \
    // 1   7 15  40
    //             \
    //              50

    Node* root = new Node(11);
    root->left = new Node(2);
    root->right = new Node(29);
    root->left->left = new Node(1);
    root->left->right = new Node(7);
    root->right->left = new Node(15);
    root->right->right = new Node(40);
    root->right->right->right = new Node(50);

    transformTree(root);
    inorder(root);

    return 0;
}
Java
// Java program to transform a BST to sum tree
import java.util.HashMap;

class Node {
    int data;
    Node left, right;

    Node(int value) {
        data = value;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to find nodes having greater value than
   // current node.
    static void findGreaterNodes(Node root, Node curr, 
                                 HashMap<Node, Integer> map) {
        if (root == null) return;

        // if value is greater than node, then increment
        // it in the map
        if (root.data > curr.data)
            map.put(curr, map.getOrDefault(curr, 0) + root.data);

        findGreaterNodes(root.left, curr, map);
        findGreaterNodes(root.right, curr, map);
    }

    static void transformToGreaterSumTree(Node curr, Node root,
                                          HashMap<Node, Integer> map) {
        if (curr == null) {
            return;
        }

        // Find all nodes greater than current node
        findGreaterNodes(root, curr, map);

        // Recursively check for left and right subtree.
        transformToGreaterSumTree(curr.left, root, map);
        transformToGreaterSumTree(curr.right, root, map);
    }

    // Function to update value of each node.
    static void preOrderTrav(Node root, HashMap<Node, Integer> map) {
        if (root == null) return;

        root.data = map.getOrDefault(root, 0);

        preOrderTrav(root.left, map);
        preOrderTrav(root.right, map);
    }
  
    static void transformTree(Node root) {
        
        // map to store greater sum for each node.
        HashMap<Node, Integer> map = new HashMap<>();
        transformToGreaterSumTree(root, root, map);

        // update the value of nodes
        preOrderTrav(root, map);
    }

    static void inorder(Node root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }

    public static void main(String[] args) {
        
        // Constructing the BST
        //     11
        //    /  \
        //   2    29
        //  / \   / \
        // 1   7 15  40
        //             \
        //              50
        Node root = new Node(11);
        root.left = new Node(2);
        root.right = new Node(29);
        root.left.left = new Node(1);
        root.left.right = new Node(7);
        root.right.left = new Node(15);
        root.right.right = new Node(40);
        root.right.right.right = new Node(50);

        transformTree(root);
        inorder(root);
    }
}
Python
# Python program to transform a BST
# to sum tree

class Node:
    def __init__(self, value):
        self.data = value
        self.left = None
        self.right = None

# Function to find nodes having greater 
# value than current node.
def findGreaterNodes(root, curr, map):
    if root is None:
        return
    
    # if value is greater than node, then increment
    # it in the map
    if root.data > curr.data:
        map[curr] += root.data

    findGreaterNodes(root.left, curr, map)
    findGreaterNodes(root.right, curr, map)

def transformToGreaterSumTree(curr, root, map):
    if curr is None:
        return

    # Find all nodes greater than current node
    map[curr] = 0
    findGreaterNodes(root, curr, map)

    # Recursively check for left and right subtree.
    transformToGreaterSumTree(curr.left, root, map)
    transformToGreaterSumTree(curr.right, root, map)

# Function to update value of each node.
def preOrderTrav(root, map):
    if root is None:
        return
    
    root.data = map.get(root, root.data)
    
    preOrderTrav(root.left, map)
    preOrderTrav(root.right, map)

def transformTree(root):
    
    # map to store greater sum for each node.
    map = {}
    transformToGreaterSumTree(root, root, map)
    
    # update the value of nodes
    preOrderTrav(root, map)

def inorder(root):
    if root is None:
        return
    inorder(root.left)
    print(root.data, end=" ")
    inorder(root.right)

if __name__ == "__main__":
    
    # Constructing the BST
    #     11
    #    /  \
    #   2    29
    #  / \   / \
    # 1   7 15  40
    #             \
    #              50
    root = Node(11)
    root.left = Node(2)
    root.right = Node(29)
    root.left.left = Node(1)
    root.left.right = Node(7)
    root.right.left = Node(15)
    root.right.right = Node(40)
    root.right.right.right = Node(50)
    
    transformTree(root)
    inorder(root)
C#
// C# program to transform a BST
// to sum tree
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int value) {
        data = value;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to find nodes having greater value
      // than current node.
    static void FindGreaterNodes(Node root, Node curr, 
                                 Dictionary<Node, int> map) {
        if (root == null) return;

        // if value is greater than node, then increment
        // it in the map
        if (root.data > curr.data)
            map[curr] += root.data;

        FindGreaterNodes(root.left, curr, map);
        FindGreaterNodes(root.right, curr, map);
    }

    static void TransformToGreaterSumTree(Node curr, Node root, 
                                          Dictionary<Node, int> map) {
        if (curr == null) {
            return;
        }

        // Find all nodes greater than
          // current node
        map[curr] = 0;
        FindGreaterNodes(root, curr, map);

        // Recursively check for left and right subtree.
        TransformToGreaterSumTree(curr.left, root, map);
        TransformToGreaterSumTree(curr.right, root, map);
    }

    // Function to update value of each node.
    static void PreOrderTrav(Node root, Dictionary<Node, int> map) {
        if (root == null) return;

        root.data = map.ContainsKey(root) ? map[root] : root.data;

        PreOrderTrav(root.left, map);
        PreOrderTrav(root.right, map);
    }
  
    static void TransformTree(Node root) {
        
        // map to store greater sum for each node.
        Dictionary<Node, int> map = new Dictionary<Node, int>();
        TransformToGreaterSumTree(root, root, map);

        // update the value of nodes
        PreOrderTrav(root, map);
    }

    static void Inorder(Node root) {
        if (root == null) {
            return;
        }
        Inorder(root.left);
        Console.Write(root.data + " ");
        Inorder(root.right);
    }

    static void Main(string[] args) {
        
        // Constructing the BST
        //     11
        //    /  \
        //   2    29
        //  / \   / \
        // 1   7 15  40
        //             \
        //              50
        Node root = new Node(11);
        root.left = new Node(2);
        root.right = new Node(29);
        root.left.left = new Node(1);
        root.left.right = new Node(7);
        root.right.left = new Node(15);
        root.right.right = new Node(40);
        root.right.right.right = new Node(50);

        TransformTree(root);
        Inorder(root);
    }
}
JavaScript
// JavaScript program to transform 
// a BST to sum tree
class Node {
    constructor(value) {
        this.data = value;
        this.left = null;
        this.right = null;
    }
}

// Function to find nodes having greater value 
// than current node.
function findGreaterNodes(root, curr, map) {
    if (root === null) return;

    // if value is greater than node, then increment
    // it in the map
    if (root.data > curr.data) {
        map.set(curr, (map.get(curr) || 0) + root.data);
    }

    findGreaterNodes(root.left, curr, map);
    findGreaterNodes(root.right, curr, map);
}

function transformToGreaterSumTree(curr, root, map) {
    if (curr === null) {
        return;
    }

    // Find all nodes greater than current node
    findGreaterNodes(root, curr, map);

    // Recursively check for left and right subtree.
    transformToGreaterSumTree(curr.left, root, map);
    transformToGreaterSumTree(curr.right, root, map);
}

// Function to update value of each node.
function preOrderTrav(root, map) {
    if (root === null) return;

    root.data = map.has(root) ? map.get(root) : 0;

    preOrderTrav(root.left, map);
    preOrderTrav(root.right, map);
}

function transformTree(root) {

    // map to store greater sum for each node.
    const map = new Map();
    transformToGreaterSumTree(root, root, map);

    // update the value of nodes
    preOrderTrav(root, map);
}

function inorder(root) {
    if (root === null) {
        return;
    }
    inorder(root.left);
    console.log(root.data + " ");
    inorder(root.right);
}

// Constructing the BST
const root = new Node(11);
root.left = new Node(2);
root.right = new Node(29);
root.left.left = new Node(1);
root.left.right = new Node(7);
root.right.left = new Node(15);
root.right.right = new Node(40);
root.right.right.right = new Node(50);

transformTree(root);
inorder(root);

Output
154 152 145 134 119 90 50 0 

Time Complexity: O(n^2), where n is the number of nodes in tree.
Auxiliary Space: O(n)

Note: This approach will give time limit exceeded (TLE) error.

[Expected Approach] Using Single Traversal – O(n) Time and O(n) Space

The idea is to traverse the tree in reverse in-order (right -> root -> left) while keeping a running sum of all previously visited nodes. The value of each node is updated to this running sum, which ensure that each node contains the sum of all nodes greater than it.

Below is the implementation of the above approach: 

C++
// C++ program to transform a BST to sum tree

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int value) {
        data = value;
        left = nullptr;
        right = nullptr;
    }
};

void transformToGreaterSumTree(Node* root, int& sum) {
    if (root == nullptr) {
        return;
    }

    // Traverse the right subtree first (larger values)
    transformToGreaterSumTree(root->right, sum);

    // Update the sum and the current node's value
    sum += root->data;
    root->data = sum - root->data;

    // Traverse the left subtree (smaller values)
    transformToGreaterSumTree(root->left, sum);
}

void transformTree(Node* root) {
  
      // Initialize the cumulative sum
    int sum = 0; 
    transformToGreaterSumTree(root, sum);
}

void inorder(Node* root) {
    if (root == nullptr) {
        return;
    }
    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}

int main() {

    // Constructing the BST
    //     11
    //    /  \
    //   2    29
    //  / \   / \
    // 1   7 15  40
    //             \
    //              50

    Node* root = new Node(11);
    root->left = new Node(2);
    root->right = new Node(29);
    root->left->left = new Node(1);
    root->left->right = new Node(7);
    root->right->left = new Node(15);
    root->right->right = new Node(40);
    root->right->right->right = new Node(50);

    transformTree(root);
    inorder(root);

    return 0;
}
C
// C program to transform a BST 
// to sum tree

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

void transformToGreaterSumTree(struct Node* root, int* sum) {
    if (root == NULL) {
        return;
    }

    // Traverse the right subtree first (larger values)
    transformToGreaterSumTree(root->right, sum);

    // Update the sum and the current node's value
    *sum += root->data;
    root->data = *sum - root->data;

    // Traverse the left subtree (smaller values)
    transformToGreaterSumTree(root->left, sum);
}

void transformTree(struct Node* root) {
  
      // Initialize the cumulative sum
    int sum = 0; 
    transformToGreaterSumTree(root, &sum);
}

void inorder(struct Node* root) {
    if (root == NULL) {
        return;
    }
    inorder(root->left);
    printf("%d ", root->data);
    inorder(root->right);
}

struct Node* createNode(int data) {
    struct Node* node = 
      (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

int main() {
  
    // Constructing the BST
    //     11
    //    /  \
    //   2    29
    //  / \   / \
    // 1   7 15  40
    //             \
    //              50

    struct Node* root = createNode(11);
    root->left = createNode(2);
    root->right = createNode(29);
    root->left->left = createNode(1);
    root->left->right = createNode(7);
    root->right->left = createNode(15);
    root->right->right = createNode(40);
    root->right->right->right = createNode(50);

    transformTree(root);
    inorder(root);
    return 0;
}
Java
// Java program to transform a 
// BST to sum tree

class Node {
    int data;
    Node left, right;

    Node(int value) {
        data = value;
        left = right = null;
    }
}

class GfG {

    static void transformToGreaterSumTree(Node root, int[] sum) {
        if (root == null) {
            return;
        }

        // Traverse the right subtree first (larger values)
        transformToGreaterSumTree(root.right, sum);

        // Update the sum and the current node's value
        sum[0] += root.data;
        root.data = sum[0] - root.data;

        // Traverse the left subtree (smaller values)
        transformToGreaterSumTree(root.left, sum);
    }

    static void transformTree(Node root) {
      
          // Initialize the cumulative sum
        int[] sum = {0}; 
        transformToGreaterSumTree(root, sum);
    }

    static void inorder(Node root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }

    public static void main(String[] args) {
      
        // Constructing the BST
        //     11
        //    /  \
        //   2    29
        //  / \   / \
        // 1   7 15  40
        //             \
        //              50

        Node root = new Node(11);
        root.left = new Node(2);
        root.right = new Node(29);
        root.left.left = new Node(1);
        root.left.right = new Node(7);
        root.right.left = new Node(15);
        root.right.right = new Node(40);
        root.right.right.right = new Node(50);

        transformTree(root);
        inorder(root);
    }
}
Python
# Python program to transform a BST to sum tree

class Node:
    def __init__(self, value):
        self.data = value
        self.left = None
        self.right = None

def transformToGreaterSumTree(root, sum):
    if root is None:
        return

    # Traverse the right subtree first (larger values)
    transformToGreaterSumTree(root.right, sum)

    # Update the sum and the current node's value
    sum[0] += root.data
    root.data = sum[0] - root.data

    # Traverse the left subtree (smaller values)
    transformToGreaterSumTree(root.left, sum)

def transformTree(root):
  
      # Initialize the cumulative sum
    sum = [0]  
    transformToGreaterSumTree(root, sum)

def inorder(root):
    if root is None:
        return
    inorder(root.left)
    print(root.data, end=" ")
    inorder(root.right)

if __name__ == "__main__":
  
    # Constructing the BST
    #     11
    #    /  \
    #   2    29
    #  / \   / \
    # 1   7 15  40
    #             \
    #              50

    root = Node(11)
    root.left = Node(2)
    root.right = Node(29)
    root.left.left = Node(1)
    root.left.right = Node(7)
    root.right.left = Node(15)
    root.right.right = Node(40)
    root.right.right.right = Node(50)

    transformTree(root)
    inorder(root)
C#
// C# program to transform a BST to sum tree

using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int value) {
        data = value;
        left = right = null;
    }
}

class GfG {
  
    static void transformToGreaterSumTree(Node root, ref int sum) {
        if (root == null) {
            return;
        }

        // Traverse the right subtree first (larger values)
        transformToGreaterSumTree(root.right, ref sum);

        // Update the sum and the current node's value
        sum += root.data;
        root.data = sum - root.data;

        // Traverse the left subtree (smaller values)
        transformToGreaterSumTree(root.left, ref sum);
    }

    static void transformTree(Node root) {
      
          // Initialize the cumulative sum
        int sum = 0; 
        transformToGreaterSumTree(root, ref sum);
    }

    static void inorder(Node root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        Console.Write(root.data + " ");
        inorder(root.right);
    }

    static void Main() {
      
        // Constructing the BST
        //     11
        //    /  \
        //   2    29
        //  / \   / \
        // 1   7 15  40
        //             \
        //              50

        Node root = new Node(11);
        root.left = new Node(2);
        root.right = new Node(29);
        root.left.left = new Node(1);
        root.left.right = new Node(7);
        root.right.left = new Node(15);
        root.right.right = new Node(40);
        root.right.right.right = new Node(50);

        transformTree(root);
        inorder(root);
    }
}
JavaScript
// JavaScript program to transform a
// BST to sum tree

class Node {
    constructor(value) {
        this.data = value;
        this.left = null;
        this.right = null;
    }
}

function transformToGreaterSumTree(root, sum) {
    if (root === null) {
        return;
    }

    // Traverse the right subtree first (larger values)
    transformToGreaterSumTree(root.right, sum);

    // Update the sum and the current node's value
    sum[0] += root.data;
    root.data = sum[0] - root.data;

    // Traverse the left subtree (smaller values)
    transformToGreaterSumTree(root.left, sum);
}

function transformTree(root) {
    let sum = [0]; // Initialize the cumulative sum
    transformToGreaterSumTree(root, sum);
}

// Function to perform in-order traversal (for testing)
function inorder(root) {
    if (root === null) {
        return;
    }
    inorder(root.left);
    console.log(root.data + " ");
    inorder(root.right);
}

// Constructing the BST
//     11
//    /  \
//   2    29
//  / \   / \
// 1   7 15  40
//             \
//              50

let root = new Node(11);
root.left = new Node(2);
root.right = new Node(29);
root.left.left = new Node(1);
root.left.right = new Node(7);
root.right.left = new Node(15);
root.right.right = new Node(40);
root.right.right.right = new Node(50);

transformTree(root);
inorder(root);

Output
154 152 145 134 119 90 50 0 

Time Complexity: O(n), where n is the number of nodes in given Binary Tree, as it does a simple traversal of the tree.
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all greater keys in BST. Examples: Input: Root of following BST 5 / \ 2 13 Output: The given BST is converted to following Binary Tree 18 / \ 20 13 Method 1: Solution: Do reverse In order traversal. Keep track of the s
15+ min read
Count pairs in BST with sum greater than K
Given a binary search tree containing N distinct nodes and a value K. The task is to count pairs in the given binary search tree whose sum is greater than the given value K. Examples: Input: 5 / \ 3 7 / \ / \ 2 4 6 8 k = 11Output: 6Explanation:There are 6 pairs which are (4, 8), (5, 7), (5, 8), (6, 7), (6, 8) and (7, 8).Input: 8 / \ 3 9 \ / \ 5 6 1
15+ min read
POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up problem-solving skills. POTD 15 October: Normal BST t
5 min read
K'th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, find the k'th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height
15+ min read
k-th Smallest in BST (Order Statistics in BST)
Given the root of a binary search tree and K as input, find Kth smallest element in BST.  For example, in the following BST, if k = 3, then the output should be 10, and if k = 5, then the output should be 14. Using Inorder (O(n) time and O(h) space) The Inorder Traversal of a BST traverses the nodes in increasing order. So the idea is to traverse t
15+ min read
Smallest subarray of size greater than K with sum greater than a given value
Given an array, arr[] of size N, two positive integers K and S, the task is to find the length of the smallest subarray of size greater than K, whose sum is greater than S. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 1, S = 8Output: 2Explanation: Smallest subarray with sum greater than S(=8) is {4, 5}Therefore, the required output is 2. Input: ar
15 min read
Smallest number in BST which is greater than or equal to N
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: Input: N = 20 Output: 21 Explanation: 21 is the smallest element greater than 20. Input: N = 18 Output: 19 Explanation: 19 is the s
9 min read
Smallest number in BST which is greater than or equal to N ( Iterative Approach)
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Examples: Input: N = 5 8 / \ 7 10 / / \ 2 9 13 Output: 7 As 7 is the smallest number in BST which is greater than N = 5. Input: N = 10 8 / \ 5 11 / \ 2 7 \ 3 Output: 11 As 11 is the smallest number in BST
8 min read
Add all greater values to every node in a given BST
Given a Binary Search Tree (BST), modify it so that all greater values in the given BST are added to every node. For example, consider the following BST. 50 / \ 30 70 / \ / \ 20 40 60 80 The above tree should be modified to following 260 / \ 330 150 / \ / \ 350 300 210 80Recommended PracticeAdd all greater values to every node in a BSTTry It!A simp
15+ min read
BST to a Tree with sum of all smaller keys
Given a Binary Search Tree(BST), convert it to a Binary Tree such that every key of the original BST is changed to a key plus the sum of all smaller keys in BST. Examples: Input: Output: Explanation: Every key of the original BST is changed to a key plus the sum of all smaller keys in BST. Approach: The idea is to use recursion to traverse the tree
8 min read
Two Sum in BST - Pair with given sum
Given the root of binary search tree (BST) and an integer sum, the task is to find if there exist a pair of elements such that their sum is equal to given sum. Example: Input: sum = 12 Output: TrueExplanation: In the binary tree above, there are two nodes (8 and 4) that add up to 12. Input: sum = 23 Output: FalseExplanation: In the binary tree abov
15+ min read
Maximum difference between frequency of two elements such that element having greater frequency is also greater
Given an array of n positive integers with many repeating elements. The task is to find the maximum difference between the frequency of any two different elements, such that the element with greater frequency is also greater in value than the second integer. Examples: Input : arr[] = { 3, 1, 3, 2, 3, 2 }. Output : 2 Frequency of 3 = 3. Frequency of
12 min read
Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which there are more greater (than a given number K) elements than elements less than or equal to K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray o
3 min read
Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
Given an integer X and a binary tree, the task is to count the number of triplet triplets of nodes such that their sum is greater than X and they have a grandparent -> parent -> child relationship. Example: Input: X = 100 10 / \ 1 22 / \ / \ 35 4 15 67 / \ / \ / \ / \ 57 38 9 10 110 312 131 414 / \ 8 39 Output: 6 The triplets are: 22 -> 15
15+ min read
Check if a Binary Tree (not BST) has duplicate values
Check if a Binary Tree (not BST) has duplicate values To check if a binary tree has duplicate values, you can follow these steps: Create a set to store the values that have been encountered so far.Start a traversal of the binary tree. For each node, check if its value is in the set. If it is, return true to indicate that the tree contains duplicate
10 min read
Build Binary Tree from BST such that it's level order traversal prints sorted data
Construct a Binary Tree from the given Binary Search Tree such that it's level order traversal outputs sorted data.Examples: Input: Output: 1 2 3 Input: Output: 1 2 3 4 5 Approach: Perform the inorder traversal of the given Binary Search Tree.Add each node in level order to the Binary Tree.Finally, print the level order traversal of the created Bin
12 min read
Check if a Binary Tree is BST : Simple and Efficient Approach
Given a Binary Tree, the task is to check whether the given binary tree is Binary Search Tree or not.A binary search tree (BST) is a node-based binary tree data structure which has the following properties. The left subtree of a node contains only nodes with keys less than the node's key.The right subtree of a node contains only nodes with keys gre
6 min read
Check if the Binary Tree contains a balanced BST of size K
Given a Binary Tree and a positive integer K. The task is to check whether the Balanced BST of size K exists in a given Binary Tree or not. If it exists then print “Yes” else print “No”. Examples: Input: K = 4, Below is the given Tree: 15 / \ 10 26 / \ / \ 5 12 25 40 / / \ 20 35 50 \ 60 Output: Yes Explanation: Subtree of the given tree with size k
13 min read
Convert a Binary Tree to BST by left shifting digits of node values
Given a Binary Tree of positive integers. The task is to convert it to a BST using left shift operations on the digits of the nodes. If it is not possible to convert the binary tree to BST then print -1. Examples: Input: 443 / \ 132 543 / \ 343 237 Output: 344 / \ 132 435 / \ 433 723 Explanation: 443 ? left shift two times ? 344 132 ? zero shift op
12 min read
Median of all nodes from a given range in a Binary Search Tree ( BST )
Given a Binary Search Tree (BST)consisting of N nodes and two nodes A and B, the task is to find the median of all the nodes in the given BST whose values lie over the range [A, B]. Examples: Input: A = 3, B = 11 Output: 6Explanation:The nodes that lie over the range [3, 11] are {3, 4, 6, 8, 11}. The median of the given nodes is 6. Input: A = 6, B
10 min read
Implement Binary Search Tree(BST) Iterator
Binary Search Trees (BSTs) are data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In situations it becomes necessary to traverse a BST in an order. For example an in order traversal visits nodes in ascending order based on their values. This article explores the creation of a BSTIterator c
6 min read
Count permutations of given array that generates the same Binary Search Tree (BST)
Given an array, arr[] of size N consisting of elements from the range [1, N], that represents the order, in which the elements are inserted into a Binary Search Tree, the task is to count the number of ways to rearrange the given array to get the same BST. Examples: Input: arr[ ] ={3, 4, 5, 1, 2}Output: 6Explanation :The permutations of the array w
10 min read
Iterative approach to check if a Binary Tree is BST or not
Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 Output: YES Explanation: Since the left subtree of each node of the tree consists of smaller valued nodes and the right subtree of each
9 min read
Deletion in Binary Search Tree (BST)
Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node.  Case 3. Delete a Node with Both Children in BST Deleting a node with b
10 min read
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output: Inorder Traversal: 8 12 20 22 25 30 40Preorder Tr
11 min read
LCA in BST - Lowest Common Ancestor in Binary Search Tree
Given two values n1 and n2 in a Binary Search Tree, find the Lowest Common Ancestor (LCA). You may assume that both values exist in the tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself). In other words, the LCA of n1
15+ min read
Insertion in Binary Search Tree (BST)
Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf
15+ min read
Searching in Binary Search Tree (BST)
Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInput: Root of the below BST Output: FalseExplanation
7 min read
Check if a Binary Tree is BST or not
Given the root of a binary tree. Check whether it is a Binary Search Tree or not. A Binary Search Tree (BST) is a node-based binary tree data structure with the following properties. All keys in the left subtree are smaller than the root and all keys in the right subtree are greater.Both the left and right subtrees must also be binary search trees.
15+ min read
Largest BST in a Binary Tree
Given a Binary Tree, the task is to return the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples: Input: Output: 3 Explanation: The below subtree is the maximum size BST: Input: Output: 5Explanation: The below subtree is the maximum size BST: Pr
13 min read
Article Tags :
Practice Tags :