One, Title Description
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.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Second, the problem solution
Method a: find all paths
- Recursively find all paths.
- The number of representatives of each path is calculated.
- Returns the sum.
List<List<Integer>> paths = null;
List<Integer> path = null;
public int sumNumbers(TreeNode root) {
paths = new ArrayList<>();
path = new ArrayList<>();
dfs(root);
int sum = 0;
for (int i = 0; i < paths.size(); i++) {
List<Integer> p = paths.get(i);
sum += getNum(p);
}
return sum;
}
//求出路径代表的数字
int getNum(List<Integer> path) {
int num = 0;
for (int i = 0; i < path.size(); i++) {
num = num * 10 + path.get(i);
}
return num;
}
//求出所有路径
void dfs(TreeNode root) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null) {
paths.add(new ArrayList<>(path));
}
dfs(root.left);
dfs(root.right);
path.remove(path.size()-1);
}
Complexity Analysis
- time complexity: ,
- Space complexity: ,
Method two: calculated traversal (top-down)
- The size of a number recorded on the pre, cur digital recording size of the current layer.
- When traversing the leaf node , it indicates that a path has been found, can be accumulated digital path.
- Recursive left subtree, right subtree.
* Note: The first inadvertently advance the settlement sum , this will lead to sum more than once.
if (root == null) {
sum += pre;
return;
}
int sum;
public int sumNumbers(TreeNode root) {
dfs(root, 0);
return sum;
}
private void dfs(TreeNode root, int pre) {
if (root == null) {
return;
}
int cur = pre * 10 + root.val;
if (root.left == null && root.right == null) {
sum += cur;
return;
}
dfs(root.left, cur);
dfs(root.right,cur);
}
Complexity Analysis
- time complexity: ,
- Space complexity: ,
Method three: Stack iteration | queue iteration
...