- Related Questions & Answers
- Print root to leaf paths without using recursion in C++ Programming.
- Print all root to leaf paths with there relative positions in C++
- Sum Root to Leaf Numbers in Python
- Program to print root to leaf paths without using recursion using C++
- Program to find leaf and non-leaf nodes of a binary tree in Python
- Program to find number of good leaf nodes pairs using Python
- Delete leaf nodes with value k in C++?
- Delete leaf nodes with value as x in C++?
- Delete leaf nodes with value k in C++ program
- Python Program to Count Number of Non Leaf Nodes of a given Tree
- Count Non-Leaf nodes in a Binary Tree in C++
- Unique Paths in Python
- Print Leaf Nodes at a given Level in C language
- Product of all leaf nodes of binary tree in C++
- Delete leaf nodes with value as x in C++ Program

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a binary tree. A node is known as insufficient if every such root to leaf path intersecting this node has sum strictly less than limit. We have to delete all insufficient nodes simultaneously, and return the root of the resulting binary tree. So if the tree is like, and the limit is 1 −

Then the output tree will be −

To solve this, we will follow these steps −

- Define a method solve(), this will take root and limit
- if node has no left and right subtree, then
- if value of root is less than 1, return null, otherwise root

- if root has left subtree, then left of root := solve(left of root, limit – value of root)
- if root has right subtree, then right of root := solve(right of root, limit – value of root)
- if root has either left subtree, or right subtree or both, then return root, otherwise null.

Let us see the following implementation to get better understanding −

class Solution(object): def sufficientSubset(self, root, limit): """ :type root: TreeNode :type limit: int :rtype: TreeNode """ if not root.left and not root.right: return None if root.val<limit else root if root.left: root.left= self.sufficientSubset(root.left,limit-root.val) if root.right: root.right = self.sufficientSubset(root.right,limit-root.val) return root if root.left or root.right else None

[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14] 1

[1,2,3,4,null,null,7,8,9,null,14]

Advertisements