Given a binary tree, where every node value is a Digit from 1-9 .Find the sum of all the numbers which are formed from root to leaf paths.
For example consider the following Binary Tree.
6 / \ 3 5 / \ \ 2 5 4 / \ 7 4 There are 4 leaves, hence 4 root to leaf paths: Path Number 6->3->2 632 6->3->5->7 6357 6->3->5->4 6354 6->5>4 654 Answer = 632 + 6357 + 6354 + 654 = 13997
The idea is to do a preorder traversal of the tree. In the preorder traversal, keep track of the value calculated till the current node, let this value be val. For every node, we update the val as val*10 plus node’s data.
Sum of all paths is 13997
Time Complexity: The above code is a simple preorder traversal code which visits every exactly once. Therefore, the time complexity is O(n) where n is the number of nodes in the given binary tree.
This article is contributed by Ramchand R. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths
- Print all root to leaf paths with there relative positions
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
- Remove nodes on root to leaf paths of length < K
- Print root to leaf paths without using recursion
- Root to leaf paths having equal lengths in a Binary Tree
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Count of root to leaf paths in a Binary Tree that form an AP
- Print all the paths from root, with a specified sum in Binary tree
- Find all root to leaf path sum of a Binary Tree
- Root to leaf path sum equal to a given number
- Find the maximum sum leaf to root path in a Binary Tree
- Sum of nodes on the longest path from root to leaf node
- Shortest root to leaf path sum equal to a given number
- Print the longest leaf to leaf path in a Binary tree
- Print the path common to the two paths from the root to the two given nodes
- Check if there is a root to leaf path with given sequence