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.
大致題意
給出一個二叉樹,從根到葉子的路徑可以構造一個數。
例如 1->2->3
可以構造為 123
給出一棵樹,求該方法在此樹上構造的數的和
舉個例子,
1
/
2 3
The root-to-leaf path 1->2 表示數字 12.
The root-to-leaf path 1->3 表示數字 13.
題解
題目型別:DFS
分析題目,實際上一個節點構造的樹的和為左子樹與節點和右子樹與節點構造數的和,很常規的dfs題目
題解如下
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
return sum(root, 0);
}
int sum(TreeNode * node, int val) {
if (node == nullptr) return 0;
val = val * 10 + node->val;
// 如果左右為空,返回自己
if (node->right == nullptr && node->left == nullptr) return val; // 左右不為空開始構造數
return sum(node->left, val) + sum(node->right, val);
}
};