VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-nodes-binary-tree/

⇱ Sum of All Nodes in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of All Nodes in a Binary Tree

Last Updated : 7 May, 2026

Given a binary tree, find the sum of all Nodes in a binary tree.

Examples:

Input: root = [15, 10, 20, 8, 12, 16, 25]

πŸ‘ 2056957867

Output: 106
Explanation: The sum of all the nodes is 15 + 10 + 20 + 8 + 12 + 16 + 25 = 106.

Input: root = [1, 3, 2]

πŸ‘ 2056957868

Output: 6
Explanation: The sum of all the nodes is 1 + 2 + 3 = 6.

Using Recursive DFS (Depth First Search) - O(n) Time O(h) Space

The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node's data. 

Consider the following tree for example to understand the flow.

πŸ‘ heightTree3

sumBT('12') = 12 + sumBT('8') + sumBT('18') = 12 + 24 + 18 = 54
because recursively 
sumBT('8') =  8 + sumBT('5') + sumBT('11') = 8 + 5 + 111 = 24
sumBT('18') = 18 + sumBT(NULL) + sumBT('NULL) = 18 + 0 + 0 = 18
sumBT("5") = 5 + sumBT(NULL), + sumBT('NULL)) = 5 + 0 + 0 = 5
sumBT("11") = 11 + sumBT(NULL) + sumBT('NULL)) = 11 + 0 + 0 = 11


Output
Sum of all the elements is: 106

Time Complexity: O(n)
Auxiliary Space: O(h), but if we consider space due to the recursion call stack then it would be O(h), where h is the height of the Tree.

Using Level Order Traversal (BFS) - O(n) Time O(n) Space

The Idea is to traverse the tree level by level using a queue (BFS). Start from the root, add each node’s value to the sum, and push its left and right children into the queue. Repeat until all nodes are processed.


Output
Sum of all elements in the binary tree is: 106

Time Complexity: O(n)
Auxiliary Space: O(n)

Using Morris Traversal - O(n) Time O(1) Space

Morris Traversal visits nodes without recursion or a stack by creating temporary links. If a node has no left child, add its value and move right. Otherwise, create or remove a link with its inorder predecessor to traverse left and then back. This ensures all nodes are visited once using O(1) extra space.

Let us understand with an example:

Input: root = [15, 10, 20, 8, 12, 16, 25]

Start from 15 -> left exists, create link -> move left

  • At 10 -> left exists, create link -> move left
  • At 8 -> no left child, add -> sum = 8
  • Back to 10 -> remove link, add -> sum = 18
  • At 12 -> no left child, add -> sum = 30
  • Back to 15 -> remove link, add -> sum = 45
  • At 20 -> left exists, create link -> move left
  • At 16 -> no left child, add -> sum = 61
  • Back to 20 -> remove link, add -> sum = 81
  • At 25 -> no left child, add -> sum = 106

All nodes are visited once. Final sum = 106


Output
Sum of all nodes in the binary tree is 106

Time Complexity: O(n) , Because of  all the nodes are traversing only once.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: