JAVA concise solution using list(one pass)


  • 0
    J
    public class Solution {
        List<Integer> nums = new ArrayList<Integer>();
        public int sumNumbers(TreeNode root) {
            if(root == null) return 0; 
            helper(root,0);
            int sum = 0;
            for(int i = 0; i < nums.size(); i++){
                sum += nums.get(i);
            }
            return sum;
        }
        public void helper(TreeNode node, int n){
            n = n * 10 + node.val;
            if(node.left == null && node.right == null){
                nums.add(n);
                return;
            }
            if(node.left != null) helper(node.left,n);
            if(node.right != null) helper(node.right,n);
        }
    }

Log in to reply
 

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