# sum root to leaf numbers

## sum root to leaf numbers

### DFS

DFS helps me resolve nearly half of the questions in leetcode.Using `result`

to save the numbers when we reach the leaf. if we did not reach the leaf make current value 10 times and plus the current nood's value, then DFS it's left and right child if it has one.

```
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 private:
12 int result;
13 public:
14 int sumNumbers(TreeNode *root) {
15 result = 0;
16 if ( !root ) {
17 return result;
18 }
19 DFS(root,0);
20 return result;
21 }
22 void DFS( TreeNode* root, int val ) {
23 val *= 10;
24 val += root->val;
25 if ( !root->left && !root->right ) {
26 result += val;
27 return;
28 }
29 if ( root->left) {
30 DFS(root->left,val);
31 }
32 if ( root->right ) {
33 DFS(root->right,val);
34 }
35 }
36 };
```