A 5-Line Recursive C# Solution Without Helper function


  • 0
    L

    By updating Node's value we can record the parent's information

    public int SumNumbers(TreeNode root) {
        if(root == null) return 0;
        if(root.left != null) root.left.val = 10 * root.val + root.left.val;
        if(root.right != null) root.right.val = 10 * root.val + root.right.val;
        int left = SumNumbers(root.left), right = SumNumbers(root.right);
        return left + right == 0 ? root.val : left + right ;
    }
    

    Below is the common way with a Helper function

    public int SumNumbers1(TreeNode root) {
        return helper(root, 0);
    }
    private int helper(TreeNode root, int curTotal){
        if(root == null) return 0;
        curTotal = curTotal * 10 + root.val;
        return root.left == null && root.right == null
               ? curTotal
               : helper(root.left, curTotal) + helper(root.right, curTotal);
    }

Log in to reply
 

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