Given a binary tree containing digits from0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3 which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path1->2
represents the number 12.
The root-to-leaf path1->3 represents the number13.
Return the sum = 12 + 13 =25.
这道题是计算二叉树所表示的数字之和,题目难度为Medium。
题目比较简单,采用深度优先的方法遍历二叉树即可,具体代码:
class Solution {
int sumNum(TreeNode* node, int num) {
if(!node) return 0;
int curNum = num*10 + node->val;
if(!node->left && !node->right) return curNum;
else return sumNum(node->left, curNum) + sumNum(node->right, curNum);
}
public:
int sumNumbers(TreeNode* root) {
return sumNum(root, 0);
}
};