# 129. Sum Root to Leaf Numbers (example)





[https://leetcode.com/problems/sum-root-to-leaf-numbers/](https://leetcode.com/problems/sum-root-to-leaf-numbers/)



1. 全域變數

````java
```java
class Solution {
    int sum = 0;
    public int sumNumbers(TreeNode root) {
        dfs(root, 0);
        return sum;
    }
    private void dfs(TreeNode node, int preSum) {
        if (node == null) {
            return;
        }
        preSum = preSum*10 + node.val;
        if (node.left == null && node.right == null) {
            sum += preSum;
        }
        dfs(node.left, preSum);
        dfs(node.right, preSum);
    }
}
```
````



trick point:&#x20;

```java
int currentSum = sum*10 + root.val;
```

```java
class Solution {
    public int sumNumbers(TreeNode root) {
        return cal(root, 0);
    }
    private int cal(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        int currentSum = sum*10 + root.val;
        if (root.left == null && root.right == null) {
            return currentSum;
        }
        return cal(root.left, currentSum) + cal(root.right, currentSum);
        
    }
}
```

上面是包在 dfs 內回傳...蠻厲害的, 解法一是比較簡單！



下面是還特別給予變數 result, umm...也不用判斷 left == null, 前面會擋住

````java
```java
class Solution {
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0, 0);
    }
    private int dfs(TreeNode node, int preSum, int result) {
        if (node == null) {
            return result; // 如果用 result = dfs(left..., 要 return result, 不然會被蓋過去, 所以還是相加吧！
        }
        int currentSum = preSum*10 + node.val;
        if (node.left == null && node.right == null) {
            result += currentSum;
            return result;
        }
        if (node.left != null) {
            result = dfs(node.left, currentSum, result);
        }
        if (node.right != null) {
            result = dfs(node.right, currentSum, result);
        }
        return result;
    }
}
```
````



## all follow this:

T: O(n)

S: O(n)

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }
    private int dfs(TreeNode node, int pre) {
        if (node == null) {
            return 0;
        }
        int val = pre*10 + node.val;
        if (node.left == null && node.right == null) {
            return val;
        }
        return dfs(node.left, val) + dfs(node.right, val);
    }
}

/***

1

pre*10 + cur.val

 */
```
