Easiest to understand C# solution recursive


  • 0
    E

    Elegant easy to understand recursive solution:

        public int SumNumbers(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return SumNumbersHelper(root, 0);
        }
        
        public int SumNumbersHelper(TreeNode node, int sumSoFar) {
            if (node == null) {
                return 0;
            }
            else {
                int currentSum = sumSoFar * 10 + node.val;
                if (node.left == null && node.right == null) {
                    return currentSum;
                }
                return SumNumbersHelper(node.left, currentSum) + SumNumbersHelper(node.right, currentSum);
            }
        }
    

Log in to reply
 

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