Sum Root to Leaf Numbers
LeetCode Problem #129 (Medium)
Problem Statement
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
Testcases
Prerequisite Knowledge
Depth-First-Search
Refer to the Prerequisite Knowledge section in Surrounded Regions:
Algorithm
Depth-First-Search Approach
Traverse through each branch of the tree and iteratively construct the number that it forms until the branch ends.
If the branch ends, add the value to the cumulative sum, stored in a global variable.
If the tree reaches the last leaf node, stop the process and return the sum value.
Code
Last updated
Was this helpful?