- Related Questions & Answers
- Program to find largest sum of any path of a binary tree in Python
- Program to find sum of longest sum path from root to leaf of a binary tree in Python
- Program to find sum each of the diagonal path elements in a binary tree in Python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest consecutive path of a binary tree in python
- Program to find longest even value path of a binary tree in Python
- Program to find sum of all elements of a tree in Python
- Sum of all subsets of a set formed by first n natural numbers
- Binary Tree Maximum Path Sum in Python
- Program to find the largest sum of the path between two nodes in a binary tree in Python
- Python Program to Find the Sum of all Nodes in a Tree
- Program to find most frequent subtree sum of a binary tree in Python
- Program to find sum of the right leaves of a binary tree in C++
- Program to find sum of widths of all subsequences of list of numbers in Python
- Program to find top view of a binary tree in Python

- 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 where each node is containing a single digit from 0 to 9. Now each path from the root to the leaf represents a number with its digits in order. We have to find the sum of numbers represented by all paths in the tree.

So, if the input is like

then the output will be 680 as 46 (4 → 6), 432 (4 → 3 → 2), 435 (4 → 3 → 5), and their sum is 913.

To solve this, we will follow these steps −

- Define a function solve() . This will take root, string:= blank string
- if root and not root.left and not root.right is non-zero, then
- return int(string + str(value of root))

- total := 0
- if left of root is not null, then
- total := total + numeric value of solve(left of root, string concatenate value of root)

- if right of root is not null, then
- total := total + numeric value of solve(right of root, string concatenate value of root)

- return total

Let us see the following implementation to get better understanding −

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=""): if root and not root.left and not root.right: return int(string + str(root.val)) total = 0 if root.left: total += int(self.solve(root.left, string + str(root.val))) if root.right: total += int(self.solve(root.right, string + str(root.val))) return total ob = Solution() root = TreeNode(4) root.left = TreeNode(6) root.right = TreeNode(3) root.right.left = TreeNode(2) root.right.right = TreeNode(5) print(ob.solve(root))

root = TreeNode(4) root.left = TreeNode(6) root.right = TreeNode(3) root.right.left = TreeNode(2) root.right.right = TreeNode(5)

913

Advertisements