讨论/《深度优先搜索》 - 练习:求根到叶子节点数字之和/
《深度优先搜索》 - 练习:求根到叶子节点数字之和
共 6 个回复
class Solution {
    public int sumNumbers(TreeNode root) {
        return sumNumbers(0, root);
    }

    public int sumNumbers(int parent, TreeNode root) {
        if (root == null) {
            return 0;
        } else if (root.left == null && root.right == null) {
            return parent * 10 + root.val;
        } else {
            int curr = parent * 10 + root.val;
            return sumNumbers(curr, root.left) + sumNumbers(curr, root.right);
        }
    }
}

C语言双百

int TreeDfs(struct TreeNode *root, int base)
{
    if ((root->left == NULL) && (root->right == NULL)) {
        return base + root->val;
    }
    int left = 0;
    int right = 0;
    if (root->left != NULL) {
        left = TreeDfs(root->left, (base + root->val) * 10);
    }
    if (root->right != NULL) {
        right = TreeDfs(root->right, (base + root->val) * 10);
    }

    return left + right;
}
int sumNumbers(struct TreeNode* root){
    return TreeDfs(root, 0);
}

你这res不是没用吗

class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        self.res = 0
        def dfs(root, value):
            if not root: return
            if not root.left and not root.right:
                self.res += root.val + 10 * value
            if root.left: dfs(root.left, 10 * value + root.val)
            if root.right: dfs(root.right, 10 * value + root.val)
        dfs(root, 0)
        return self.res
class Solution {
    int res = 0;
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }
    private int dfs(TreeNode node, int sum){
        if(node == null) return 0;
        sum = sum * 10 + node.val;
        if(node.left == null && node.right == null){
            return sum; 
        }
        return dfs(node.left, sum) + dfs(node.right, sum);
    }
}
class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        if not root :return 0
        res = 0 
        def dfs(root,pth):
            nonlocal res
            if not root.left and not root.right:
                res += reduce(lambda x,y:10 * x + y,pth+[root.val])
            else:
                if root.left : dfs(root.left,pth+[root.val])
                if root.right : dfs(root.right,pth+[root.val])
        dfs(root,[])
        return res