leetcode@ [129] Sum Root to Leaf Numbers (DFS)

时间:2021-07-14 15:02:40

https://leetcode.com/problems/sum-root-to-leaf-numbers/

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.

/**
* 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:
void travel(vector<vector<int> >& nums, vector<int>& load, TreeNode* root) {
if(!(root->left) && !(root->right)) {
nums.push_back(load);
return;
} if(root->left) {
load.push_back(root->left->val);
travel(nums, load, root->left);
load.pop_back();
}
if(root->right) {
load.push_back(root->right->val);
travel(nums, load, root->right);
load.pop_back();
}
}
int sumNumbers(TreeNode* root) {
if(root == NULL) return ; vector<vector<int> > nums;
vector<int> load;
int res = ; load.push_back(root->val);
travel(nums, load, root); for(int i=; i<nums.size(); ++i) {
int rhs = ;
for(int j=; j<nums[i].size(); ++j) {
rhs = rhs * + nums[i][j];
}
res += rhs;
}
return res;
}
};