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 find sum of all numbers formed by path of a binary tree in python
Suppose we have a binary tree where each node contains a single digit from 0 to 9. Each path from the root to a leaf represents a number with its digits in order. We need to find the sum of all numbers represented by these root-to-leaf paths.
So, if the input is like ?
Then the output will be 913 because the paths are: 46 (4 ? 6), 432 (4 ? 3 ? 2), 435 (4 ? 3 ? 5), and their sum is 46 + 432 + 435 = 913.
Algorithm
To solve this problem, we will follow these steps ?
- Define a recursive function
solve()that takes the current node and a string representing the path so far - If the current node is a leaf (no left or right children), convert the complete path string to an integer and return it
- Otherwise, recursively call the function for left and right children, appending the current node's value to the path string
- Return the sum of results from both subtrees
Example
class TreeNode:
def __init__(self, data, left=None, right=None):
self.val = data
self.left = left
self.right = right
class Solution:
def solve(self, root, string=""):
# Base case: if it's a leaf node
if root and not root.left and not root.right:
return int(string + str(root.val))
total = 0
# Recursively process left subtree
if root.left:
total += self.solve(root.left, string + str(root.val))
# Recursively process right subtree
if root.right:
total += self.solve(root.right, string + str(root.val))
return total
# Create the binary tree
ob = Solution()
root = TreeNode(4)
root.left = TreeNode(6)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
root.right.right = TreeNode(5)
# Find sum of all root-to-leaf paths
result = ob.solve(root)
print(f"Sum of all path numbers: {result}")
Sum of all path numbers: 913
How It Works
The algorithm works by performing a depth-first traversal of the tree ?
- For each node, we build a string representing the path from root to current node
- When we reach a leaf node, we convert the complete path string to an integer
- The total sum is calculated by adding up all the integers formed by different root-to-leaf paths
Alternative Implementation
Here's a more concise version using integer arithmetic instead of string concatenation ?
class Solution:
def solve_numeric(self, root, current_number=0):
if not root:
return 0
# Build number by shifting digits left and adding current digit
current_number = current_number * 10 + root.val
# If leaf node, return the number formed
if not root.left and not root.right:
return current_number
# Sum results from both subtrees
return (self.solve_numeric(root.left, current_number) +
self.solve_numeric(root.right, current_number))
# Test with same tree
ob = Solution()
root = TreeNode(4)
root.left = TreeNode(6)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
root.right.right = TreeNode(5)
result = ob.solve_numeric(root)
print(f"Sum using numeric approach: {result}")
Sum using numeric approach: 913
Conclusion
Both approaches solve the problem by traversing all root-to-leaf paths and summing the numbers they represent. The string concatenation method is more intuitive, while the numeric approach is more memory-efficient as it avoids creating string objects.
