
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find sum of all elements of a tree in Python
Suppose we have a binary tree containing some values, we have to find the sum of all values in the tree.
So, if the input is like
then the output will be 14
To solve this, we will follow these steps −
Define a function recurse() . This will take node
val := value of node
if left of node is not null, then
val := val + recurse(left of node)
if right of node is not−null, then
val := val + recurse(right of node)
return val
From the main method, do the following −
if not root is non−zero, then
return 0
return recurse(root)
Let us see the following implementation to get better understanding −
Example
class TreeNode: def __init__(self, data, left = None, right = None): self.val = data self.left = left self.right = right class Solution: def recurse(self, node): val = node.val if node.left: val += self.recurse(node.left) if node.right: val += self.recurse(node.right) return val def solve(self, root): if not root: return 0 return self.recurse(root) ob = Solution() root = TreeNode(2) root.right = TreeNode(4) root.right.left = TreeNode(3) root.right.right = TreeNode(5) print(ob.solve(root))
Input
root = TreeNode(2) root.right = TreeNode(4) root.right.left = TreeNode(3) root.right.right = TreeNode(5)
Output
14
- Related Articles
- Python Program to Find the Sum of all Nodes in a Tree
- Python Program to Find the Sum of All Nodes in a Binary Tree
- Program to find sum of all numbers formed by path of a binary tree in python
- Program to find sum each of the diagonal path elements in a binary tree in Python
- Python program to find sum of elements in list
- Program to find sum of unique elements in Python
- Program to find largest sum of any path of a binary tree in Python
- Program to find maximum sum of non-adjacent nodes of a tree in Python
- Program to find most frequent subtree sum of a binary tree in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find sum of longest sum path from root to leaf of a binary tree in Python
- Program to find sum of beauty of all substrings in Python
- Find sum of elements in list in Python program
- Python program to find the sum of all items in a dictionary
- Program to find largest sum of non-adjacent elements of a list in Python

Advertisements