Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to delete all leaves with even values from a binary tree in Python
Suppose we have a binary tree, we will repeatedly delete all leaves that have even values. After deleting all even-valued leaves, if only the root remains and it has an even value, that will be deleted as well.
So, if the input is like ?
then the output will be ?
Algorithm
To solve this problem, we will follow these steps ?
Define a function solve() that takes root as parameter
If root is null, then return null
Recursively process left subtree: left of root := solve(left of root)
Recursively process right subtree: right of root := solve(right of root)
If root is a leaf node and its data is even, then return null
Return root
Implementation
Let us see the following implementation to get better understanding ?
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def inorder(root):
if root:
inorder(root.left)
print(root.data, end=', ')
inorder(root.right)
class Solution:
def solve(self, root):
if not root:
return None
root.left = self.solve(root.left)
root.right = self.solve(root.right)
if not root.left and not root.right and root.data % 2 == 0:
return None
return root
# Example usage
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print("Original tree (inorder):")
inorder(root)
print()
root = ob.solve(root)
print("After removing even leaves (inorder):")
inorder(root)
Original tree (inorder): 12, 13, 4, 16, 7, 14, 22, After removing even leaves (inorder): 13, 16, 7, 14,
How It Works
The algorithm uses a post-order traversal approach:
Base case: If the node is null, return null
Recursive processing: First process left and right subtrees
Leaf check: After processing children, check if current node is a leaf with even value
Deletion: If it's an even leaf, return null to delete it; otherwise return the node
The process continues until no more even-valued leaves can be removed.
Conclusion
This solution efficiently removes all even-valued leaves from a binary tree using recursive post-order traversal. The algorithm ensures that after each deletion, newly formed leaves are also checked for even values until no more deletions are possible.
