Java Solution


  • 0
    I
    public class Solution {
        int sum;
        public int sumNumbers(TreeNode root) {
            sum = 0;
            if(root == null) return sum;
            DFS(root, "");
            return sum;
            
        }
        private void DFS(TreeNode node, String str) {
            if(node == null) return;
            if(node.left == null && node.right == null) {
                sum += Integer.parseInt(str + node.val);
                return;
            }
            if(node.left != null) DFS(node.left, str + node.val);
            if(node.right != null) DFS(node.right, str + node.val);
        }
    }
    

Log in to reply
 

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