Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Example 1:
Input: root = [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer.
Example 2:
Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1]
Example 3:
Input: root = [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1]
Constraints:
[1, 200].Node.val is either 0 or 1.This approach uses post-order traversal to traverse each subtree and decide if it should be pruned. Starting from the leaf nodes, it recursively checks if a subtree contains a 1. If a subtree doesn't contain any 1s, it returns null. This way, when the recursion unwinds, only relevant subtrees are kept.
The provided C code represents a function that conducts a post-order traversal starting from the given root node. It uses recursion to visit each node, first addressing the left and right subtrees. If a node's value is 0 and both its subtrees are NULL, the node is pruned by freeing its memory and returning NULL. Otherwise, the node is returned intact. The traversal ensures all subtrees without a 1 are effectively pruned away.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N), where N is the number of nodes, since each node is visited once.
Space Complexity: O(H), where H is the height of the tree, due to the recursive stack space.
By utilizing an iterative traversal using a stack, the tree can be pruned without recursion. This approach mimics the recursion stack by using an explicit stack to manage nodes that need to be processed. Once the subtree rooted at a node is evaluated, decisions are made to prune or retain nodes based on whether a 1 is found.
The C implementation employs a boolean helper function, containsOne, which verifies if any subtree contains the value 1. The iterative sense is simulated by the helper function instead of explicit stack management. Nodes without 1 in their subtrees are trimmed, promoting a structured pruning process.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N), as we are ensuring every node is visited.
Space Complexity: O(H), attributed to the height of the tree in terms of stack use.
| Approach | Complexity |
|---|---|
| Approach 1: Post-order Traversal | Time Complexity: O(N), where N is the number of nodes, since each node is visited once. |
| Approach 2: Iterative Post-order Traversal | Time Complexity: O(N), as we are ensuring every node is visited. |
Trim a Binary Search Tree - Leetcode 669 - Python • NeetCode • 20,403 views views
Watch 9 more video solutions →Practice Binary Tree Pruning with our built-in code editor and test cases.
Practice on FleetCode