Open In App

Remove all nodes which lie on a path having sum less than k

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

Given a binary tree, a complete path is defined as a path from a root to a leaf. The sum of all nodes on that path is defined as the sum of that path. Given the number k, the task is to remove all nodes that lie on a path with a sum less than k.

Note: A node can be part of multiple paths. So we have to delete it only in case when all paths from it have a sum less than k.

Input: k= 20

remove_all_nodes_which_lie_on_a_path_having_sum_less_than_k_1_1x


Output:

remove_all_nodes_which_lie_on_a_path_having_sum_less_than_k_2_1x


Explanation: Nodes with values 8 and 6 are deleted because the path sum from root to node with value 8 is 15 and the path sum from root to node with value 6 is 10.

Approach:

The idea is to traverse the binary tree recursively. At each node, decrement the required sum of the path. At the end of paths, check if the sum is less than equal to 0. If it is yes, then return true (meaning this path has sum >= k). Else return false. For the nodes, if false is returned by left and right subtree, then delete the current node and return false. If false is returned by only one subtree, then set the corresponding pointer to null. Then return true.

Below is the implementation of the above approach:

C++
// C++ program to Remove all nodes which
// don’t lie in any path with sum>= k
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

bool pruneTree(Node* root, int k) {
    
    // If path has ended, check if it 
    // satisfies the sum.
    if (root == nullptr) return k<=0;
    
    // Check for left and right subtrees.
    bool left = pruneTree(root->left, k-root->data);
    bool right = pruneTree(root->right, k-root->data);
    
    // If any path on left or right subtree does not 
    // have required sum, then delete the current Node
    // and return false.
    if (left==false && right==false) {
        delete(root);
        return false;
    }
    
    // Set left node as null, if it has been
    // deleted.
    else if (left == false) {
        root->left = nullptr;
    }
    
    // Set right node as null, if it has been
    // deleted.
    else if (right == false) {
        root->right = nullptr;
    }
    
    return true;
}

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

int main() {
    
    // Binary tree
    //       1
    //      / \
    //     2   3
    //   / \    \
    //  3   5    2
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(3);
    root->left->right = new Node(5);
    root->right->right = new Node(2);
    
    int k = 7;
    pruneTree(root, k); 
    inOrder(root);
    return 0;
}
C
// C program to Remove all nodes which
// don’t lie in any path with sum>= k
#include <stdio.h>
#include <stdlib.h>

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

// Function to prune the tree
int pruneTree(struct Node* root, int k) {
    
    // If path has ended, check if it
    // satisfies the sum.
    if (root == NULL) return k <= 0;
    
    // Check for left and right subtrees.
    int left = pruneTree(root->left, k - root->data);
    int right = pruneTree(root->right, k - root->data);
    
    // If any path on left or right subtree does not
    // have required sum, then delete the current Node
    // and return false.
    if (left == 0 && right == 0) {
        free(root);
        return 0;
    }
    
    // Set left node as null, if it has
  	// been deleted.
    else if (left == 0) {
        root->left = NULL;
    }
    
    // Set right node as null, if it has
  	// been deleted.
    else if (right == 0) {
        root->right = NULL;
    }
    
    return 1;
}

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

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

int main() {
    
    // Binary tree
    //       1
    //      / \
    //     2   3
    //   / \    \
    //  3   5    2
    struct Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(3);
    root->left->right = createNode(5);
    root->right->right = createNode(2);
    
    int k = 7;
    pruneTree(root, k); 
    inOrder(root);
    return 0;
}
Java
// Java program to Remove all nodes which
// don’t lie in any path with sum>= k
import java.util.*;

class Node {
    int data;
    Node left, right;

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

class GfG {
    
    // Function to prune the tree
    static boolean pruneTree(Node root, int k) {
        if (root == null) return k <= 0;

        boolean left = pruneTree(root.left, k - root.data);
        boolean right = pruneTree(root.right, k - root.data);

        if (!left && !right) {
            return false;
        } else if (!left) {
            root.left = null;
        } else if (!right) {
            root.right = null;
        }

        return true;
    }

    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) {
        
        // Binary tree
        //       1
        //      / \
        //     2   3
        //   / \    \
        //  3   5    2
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.right = new Node(2);

        int k = 7;
        pruneTree(root, k);
        inOrder(root);
    }
}
Python
# Python program to Remove all nodes which
# don’t lie in any path with sum>= k

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

# Function to prune the tree
def pruneTree(root, k):
    
    # If path has ended, check if it
    # satisfies the sum.
    if root is None:
        return k <= 0
    
    # Check for left and right subtrees.
    left = pruneTree(root.left, k - root.data)
    right = pruneTree(root.right, k - root.data)
    
    # If any path on left or right subtree does not
    # have required sum, then delete the current Node
    # and return False.
    if not left and not right:
        return False
    
    # Set left node as None, if it has
    # been deleted.
    elif not left:
        root.left = None
    
    # Set right node as None, if it has 
    # been deleted.
    elif not right:
        root.right = None
    
    return True

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

if __name__ == "__main__":
    
    # Binary tree
    #       1
    #      / \
    #     2   3
    #   / \    \
    #  3   5    2
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(3)
    root.left.right = Node(5)
    root.right.right = Node(2)

    k = 7
    pruneTree(root, k)
    inOrder(root)
C#
// C# program to Remove all nodes which
// don’t lie in any path with sum>= k
using System;
using System.Collections.Generic;

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

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

class GfG {

    // Function to prune the tree
    static bool pruneTree(Node root, int k) {
        if (root == null) return k <= 0;

        bool left = pruneTree(root.left, k - root.data);
        bool right = pruneTree(root.right, k - root.data);

        if (!left && !right) {
            return false;
        } else if (!left) {
            root.left = null;
        } else if (!right) {
            root.right = null;
        }

        return true;
    }

    static void inOrder(Node root) {
        if (root == null) return;

        inOrder(root.left);
        Console.Write(root.data + " ");
        inOrder(root.right);
    }

    static void Main(string[] args) {
        
        // Binary tree
        //       1
        //      / \
        //     2   3
        //   / \    \
        //  3   5    2
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(3);
        root.left.right = new Node(5);
        root.right.right = new Node(2);

        int k = 7;
        pruneTree(root, k);
        inOrder(root);
    }
}
JavaScript
// JavaScript program to Remove all nodes which
// don’t lie in any path with sum>= k

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

// Function to prune the tree
function pruneTree(root, k) {
    if (root === null) return k <= 0;

    let left = pruneTree(root.left, k - root.data);
    let right = pruneTree(root.right, k - root.data);

    if (!left && !right) {
        return false;
    } else if (!left) {
        root.left = null;
    } else if (!right) {
        root.right = null;
    }

    return true;
}

function inOrder(root) {
    if (root === null) return;

    inOrder(root.left);
    console.log(root.data);
    inOrder(root.right);
}

// Binary tree
//       1
//      / \
//     2   3
//   / \    \
//  3   5    2
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.right = new Node(2);

let k = 7;
pruneTree(root, k);
inOrder(root);

Output
2 5 1 

Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space: O(h), where h is the height of the tree.


Next Article
Article Tags :
Practice Tags :

Similar Reads