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.
题意:一个二叉树每个节点是一个0-9的数字,从根节点到叶子节点可以看做是一个数字,求所有数字的和。
思路:用深度优先搜索求出每个根节点到叶子节点代表的数字,最后求和即可。
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);
}
}
网友评论