Super simple, DFS Solution


  • 12
    S
    public class Solution {
        public int sumNumbers(TreeNode root) {
            return sumNumbers(root, 0);
        }
        
        private int sumNumbers(TreeNode root, int sum){
            if(root == null) return 0;
            if(root.left == null && root.right == null)
                return sum + root.val;
            
            return sumNumbers(root.left, (sum + root.val) * 10) + sumNumbers(root.right, (sum + root.val) * 10);
            
        }
    }

Log in to reply
 

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