Medium
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.
For example,
1
/ \
2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
太久沒有嘗過不看答案直接做出來的滋味了,這道題滿足了一下我。看了題之后很容易就聯(lián)想到了pathSum這一類跟root to leaf path相關(guān)的題,所以思路也比較清晰了,就是用DFS把所有路徑遍歷出來,最后來處理數(shù)字和加法就可以了。 這里依舊要注意一下,res.add(path)是不行的,因為path變空了之后res里面將什么也沒有, 必須要寫成res.add(new ArrayList<>(path)). 這樣不管path之后怎么變,我copy過來的path永遠(yuǎn)會保持現(xiàn)在的樣子,相當(dāng)于我只是把path里的元素copy過來了,并沒有copy path的reference。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
int sum = 0;
List<Integer> path = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
if (root == null){
return sum;
}
helper(root, path, res);
for (List<Integer> list : res){
int pathSum = 0;
for (Integer i : list){
pathSum *= 10;
pathSum += i;
}
sum += pathSum;
}
return sum;
}
private void helper(TreeNode root, List<Integer> path, List<List<Integer>> res){
if (root == null){
return;
}
path.add(root.val);
if (root.left == null && root.right == null){
res.add(new ArrayList<>(path));
}
helper(root.left, path, res);
helper(root.right, path, res);
path.remove(path.size() - 1);
}
}