DFS plus sum control with java solution


  • 0
    R

    public int sumNumbers(TreeNode root) {
    if(root == null) return 0;
    return dfs(root, 0, 0);
    }
    public int dfs(TreeNode root, int num, int sum) {
    // corner root
    if(root == null) return sum;
    num = num*10 + root.val;
    if(root.left == null && root.right == null) {
    sum += num;
    return sum;
    }
    sum = dfs(root.left, num, sum) + dfs(root.right, num, sum);
    return sum;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.