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.
DFS
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> st;
int ans = 0;
int sumNumbers(TreeNode *root) {
if(root==NULL) return ans;
st.push_back(root->val);
if(root->left==NULL&&root->right==NULL){
int a = 0;
int size = st.size();
for(int i=0;i<size;i++){
a*=10;
a+=st[i];
}
ans += a;
return ans;
}
//return sumNumbers(root->left)+sumNumbers(root->right);
sumNumbers(root->left);
if(root->left !=NULL) st.erase(st.end()-1);
sumNumbers(root->right);
if(root->right !=NULL) st.erase(st.end()-1);
return ans;
}
};