Remove all nodes which lie on a path having sum less than k
Last Updated :
19 Oct, 2024
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
Output:
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);
Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space: O(h), where h is the height of the tree.
Similar Reads
Binary Tree Data Structure A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina
15+ min read
Properties of Binary Tree This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina
4 min read
Applications, Advantages and Disadvantages of Binary Tree A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
2 min read
Binary Tree (Array implementation) Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth of Binary Tree Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.Examples:Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has
11 min read
Insertion in a Binary Tree in level order Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.Examples:Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.Approach:The
8 min read
Deletion in a Binary Tree Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Enumeration of Binary Trees A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read
Types of Binary Tree