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)