Open In App

Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K

Last Updated : 29 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree and an integer k, the task is to delete nodes from the given Tree such that the sum of all nodes of all remaining root-to-leaf paths is at least k.

Examples:

Input: k = 27

remove-nodes-from-binary-tree-such-that-sum-of-all-remaining-root-to-leaf-paths-is-atleast-k

Output: 5 4 8 5 6 11
Explanation:
Below are the paths whose sum is less than 27:

  • 5 -> 3 -> 9: Path Sum = 5 + 3 + 9 = 17.
  • 5 -> 4 -> 9: Path Sum = 5 + 4 + 9 = 18.
  • 5 -> 4 -> 8 -> 5 -> 2: Path Sum = 5 + 4 + 8 + 5 + 2 = 24.

Below is the tree after deleting the required nodes that such that sum of all paths is at least 27:

remove-nodes-from-binary-tree-such-that-sum-of-all-remaining-root-to-leaf-paths-is-atleast-k-2

Approach:

The idea is to use recursion and perform the Postorder Traversal and delete those nodes whose addition to the path sum is less than k.

Follow the steps below to solve the problem:

  • Perform the Post Order Traversal on the given Tree and during this traversal pass the sum of all nodes from the root node to each node.
  • During traversal, if we reach the leaf node then check if the sum of all nodes till that node is less than k?. If found to be true, remove that node by returning the NULL node from that node.
  • Repeat the above step for every leaf node encounters in the update tree.
  • After the above steps, print the Preorder Traversal of the modified Tree.

Below is the implementation of the above approach:

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

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

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

// Utility function that deletes nodes
// from the Tree such that every root
// to leaf path sum is at least K
Node *removePathLessThanK(Node *node, int k, int sum) {
    
    // if node is null return
    if (node == nullptr) {
        return nullptr;
    }

    // Recurse to the left
    if (node->left != nullptr) {
        node->left = removePathLessThanK(
                     node->left, k,
                     sum + node->left->data);
    }

    // Recurse to the right
    if (node->right != nullptr) {
        node->right = removePathLessThanK(
                      node->right, k,
                      sum + node->right->data);
    }

    // Check path sum at leaf node
    // is lesser than K, return NULL
    if (node->left == nullptr && 
        node->right == nullptr && sum < k) {
        node = nullptr;
        return node;
    }

    return node;
}

void viewTree(Node *node) {
    
    if (node != nullptr)  {
        cout << node->data << " ";
        viewTree(node->left);
        viewTree(node->right);
    }
}

// Function that deletes the nodes
// from the Tree such that every root
// to leaf path sum is at least K
void removePathLessThanKUtil(Node *node, int k, int sum) {
    
    // Function Call to delete Nodes
    Node *result = removePathLessThanK(node, k, sum);
    
    // Preorder Traversal of the
    // modified Tree
    viewTree(result);
}

int main() {
    
    int k = 27;

    // Given Binary Tree
  	//                5
    //              /   \
    //            4       3
    //          /   \      \
    //         9     8      9
    //             /   \      \
    //            5     11     4
    //          /   \
    //         6     2
    Node *root = nullptr;
    root = new Node(5);
    root->right = new Node(3);
    root->left = new Node(4);
    root->left->left = new Node(9);
    root->right->right = new Node(9);
    root->left->right = new Node(8);
    root->left->right->right = new Node(11);
    root->left->right->left = new Node(5);
    root->left->right->left->left = new Node(6);
    root->left->right->left->right = new Node(2);
    root->right->right->right = new Node(4);

    removePathLessThanKUtil(root, k, root->data);
}
Java
// Java program for the above approach
import java.util.*;

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

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

class GfG {

    // Utility function that deletes nodes
    // from the Tree such that every root
    // to leaf path sum is at least k
    static Node removePathLessThanK(Node node, int K, int sum) {
        
        // if node is null return
        if (node == null) {
            return null;
        }

        // Recurse to the left
        if (node.left != null) {
            node.left = removePathLessThanK
              			(node.left, K, sum + node.left.data);
        }

        // Recurse to the right
        if (node.right != null) {
            node.right = removePathLessThanK
              			(node.right, K, sum + node.right.data);
        }

        // Check path sum at leaf node
        // is lesser than K, return NULL
        if (node.left == null && node.right == null && sum < K) {
            node = null;
            return node;
        }

        // Otherwise return the
        // current node as it is
        return node;
    }

    // Function to print the preorder
    // traversal of the Tree
    static void viewTree(Node node) {
        
        // If node is not NULL
        if (node != null)  {
            
            // Print the node
            System.out.print(node.data + " ");

            // Left and Right Traversal
            viewTree(node.left);
            viewTree(node.right);
        }
    }

    // Function that deletes the nodes
    // from the Tree such that every root
    // to leaf path sum is at least K
    static void removePathLessThanKUtil
      					(Node node, int K, int sum) {
        
        // Function Call to delete Nodes
        Node result = removePathLessThanK(node, K, sum);
        
        // Preorder Traversal of the
        // modified Tree
        viewTree(result);
    }

    public static void main(String[] args) {
        
        int K = 27;

        // Given Binary Tree
        //                5
        //              /   \
        //            4       3
        //          /   \      \
        //         9     8      9
        //             /   \      \
        //            5     11     4
        //          /   \
        //         6     2
        Node root = null;
        root = new Node(5);
        root.right = new Node(3);
        root.left = new Node(4);
        root.left.left = new Node(9);
        root.right.right = new Node(9);
        root.left.right = new Node(8);
        root.left.right.right = new Node(11);
        root.left.right.left = new Node(5);
        root.left.right.left.left = new Node(6);
        root.left.right.left.right = new Node(2);
        root.right.right.right = new Node(4);
      
        removePathLessThanKUtil(root, K, root.data);
    }
}
Python
# Python program for the above approach

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

# Utility function that deletes nodes
# from the Tree such that every root
# to leaf path sum is at least K
def removePathLessThanK(node, K, sum):
    
    # if node is null return
    if node is None:
        return None

    # Recurse to the left
    if node.left is not None:
        node.left = removePathLessThanK \
        			(node.left, K, sum + node.left.data)

    # Recurse to the right
    if node.right is not None:
        node.right = removePathLessThanK \
        			(node.right, K, sum + node.right.data)

    # Check path sum at leaf node
    # is lesser than K, return NULL
    if node.left is None and node.right \
    				is None and sum < K:
        node = None
        return node

    return node

def viewTree(node):
    
    # If node is not NULL
    if node is not None:
        
        # Print the node
        print(node.data, end=" ")

        # Left and Right Traversal
        viewTree(node.left)
        viewTree(node.right)

# Function that deletes the nodes
# from the Tree such that every root
# to leaf path sum is at least K
def removePathLessThanKUtil(node, K, sum):
    
    # Function Call to delete Nodes
    result = removePathLessThanK(node, K, sum)
    
    # Preorder Traversal of the
    # modified Tree
    viewTree(result)

if __name__ == "__main__":
    
    K = 27

    # Given Binary Tree
    #                5
    #              /   \
    #            4       3
    #          /   \      \
    #         9     8      9
    #             /   \      \
    #            5     11     4
    #          /   \
    #         6     2
    root = Node(5)
    root.right = Node(3)
    root.left = Node(4)
    root.left.left = Node(9)
    root.right.right = Node(9)
    root.left.right = Node(8)
    root.left.right.right = Node(11)
    root.left.right.left = Node(5)
    root.left.right.left.left = Node(6)
    root.left.right.left.right = Node(2)
    root.right.right.right = Node(4)

    removePathLessThanKUtil(root, K, root.data)
C#
// C# program for the above approach
using System;

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

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

class GfG {

    // Utility function that deletes nodes
    // from the Tree such that every root
    // to leaf path sum is at least K
    static Node removePathLessThanK(Node node, int K, int sum) {
        
        // if node is null return
        if (node == null) {
            return null;
        }

        // Recurse to the left
        if (node.left != null) {
            node.left = removePathLessThanK
              			(node.left, K, sum + node.left.data);
        }

        // Recurse to the right
        if (node.right != null) {
            node.right = removePathLessThanK
              			(node.right, K, sum + node.right.data);
        }

        // Check path sum at leaf node
        // is lesser than K, return NULL
        if (node.left == null && node.right == null && sum < K) {
            node = null;
            return node;
        }

        return node;
    }
  
    static void viewTree(Node node) {
        
        // If node is not NULL
        if (node != null)  {
            
            Console.Write(node.data + " ");
            viewTree(node.left);
            viewTree(node.right);
        }
    }

    // Function that deletes the nodes
    // from the Tree such that every root
    // to leaf path sum is at least K
    static void removePathLessThanKUtil
      				(Node node, int K, int sum) {
        
        // Function Call to delete Nodes
        Node result = removePathLessThanK(node, K, sum);
        
        // Preorder Traversal of the
        // modified Tree
        viewTree(result);
    }

    static void Main() {
      
        int K = 27;

        // Given Binary Tree
        //                5
        //              /   \
        //            4       3
        //          /   \      \
        //         9     8      9
        //             /   \      \
        //            5     11     4
        //          /   \
        //         6     2
        Node root = null;
        root = new Node(5);
        root.right = new Node(3);
        root.left = new Node(4);
        root.left.left = new Node(9);
        root.right.right = new Node(9);
        root.left.right = new Node(8);
        root.left.right.right = new Node(11);
        root.left.right.left = new Node(5);
        root.left.right.left.left = new Node(6);
        root.left.right.left.right = new Node(2);
        root.right.right.right = new Node(4);
        removePathLessThanKUtil(root, K, root.data);
    }
}
JavaScript
// JavaScript program for the above approach

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

// Utility function that deletes nodes
// from the Tree such that every root
// to leaf path sum is at least K
function removePathLessThanK(node, K, sum) {

    // if node is null return
    if (node === null) {
        return null;
    }

    // Recurse to the left
    if (node.left !== null) {
        node.left = removePathLessThanK
        			(node.left, K, sum + node.left.data);
    }

    // Recurse to the right
    if (node.right !== null) {
        node.right = removePathLessThanK
        			(node.right, K, sum + node.right.data);
    }

    // Check path sum at leaf node
    // is lesser than K, return NULL
    if (node.left === null && node.right === null 
    						&& sum < K) {
        node = null;
        return node;
    }

    return node;
}

function viewTree(node) {

    // If node is not NULL
    if (node !== null) {

        console.log(node.data + " ");
        viewTree(node.left);
        viewTree(node.right);
    }
}

// Function that deletes the nodes
// from the Tree such that every root
// to leaf path sum is at least K
function removePathLessThanKUtil(node, K, sum) {

    // Function Call to delete Nodes
    let result = removePathLessThanK(node, K, sum);

    // Preorder Traversal of the
    // modified Tree
    viewTree(result);
}

let K = 27;

// Given Binary Tree
//                5
//              /   \
//            4       3
//          /   \      \
//         9     8      9
//             /   \      \
//            5     11     4
//          /   \
//         6     2
let root = new Node(5);
root.right = new Node(3);
root.left = new Node(4);
root.left.left = new Node(9);
root.right.right = new Node(9);
root.left.right = new Node(8);
root.left.right.right = new Node(11);
root.left.right.left = new Node(5);
root.left.right.left.left = new Node(6);
root.left.right.left.right = new Node(2);
root.right.right.right = new Node(4);

removePathLessThanKUtil(root, K, root.data);

Output
5 4 8 5 6 11 

Time Complexity: O(n), where n is the number of nodes in the given Tree.
Auxiliary Space: O(h)


Next Article

Similar Reads