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.
題意:一個二叉樹每個節(jié)點是一個0-9的數(shù)字,從根節(jié)點到葉子節(jié)點可以看做是一個數(shù)字,求所有數(shù)字的和。
思路:用深度優(yōu)先搜索求出每個根節(jié)點到葉子節(jié)點代表的數(shù)字,最后求和即可。
public int res = 0;
public int sumNumbers(TreeNode root) {
if (root == null) {
return res;
}
dfs(root, 0);
return res;
}
private void dfs(TreeNode node, int curSum) {
curSum = curSum * 10 + node.val;
if (node.left == null && node.right == null) {
res += curSum;
return;
}
if (node.left != null) {
dfs(node.left, curSum);
}
if (node.right != null) {
dfs(node.right, curSum);
}
}