Bootstrap

【回溯】129. 求根节点到叶节点数字之和

题目链接:. - 力扣(LeetCode)

套用的代码随想录回溯的思路,ac代码如下

class Solution {
    int now = 0;
    int ans = 0;

    public int sumNumbers(TreeNode root) {
        now = root.val;
        dfs(root);
        return ans;
    }

    void dfs(TreeNode root) {
        if (root.left == null && root.right == null) {
            ans += now;
            return;
        }
        if (root.left != null) {
            now = now * 10 + root.left.val;
            dfs(root.left);
            now = (now - root.left.val) / 10;
        }
        if (root.right != null) {
            now = now * 10 + root.right.val;
            dfs(root.right);
            now = (now - root.right.val) / 10;
        }

    }
}

;