My first solution:
class Solution { private int sum =0; public int sumNumbers(TreeNode root) { preOrder(root, ""); return sum; } private void preOrder(TreeNode root, String numString){ if(root==null) return; if(root.left==null&&root.right==null){ int num = Integer.valueOf(numString+root.val); sum+=num; return; } preOrder(root.left, numString+root.val); preOrder(root.right, numString+root.val); } }
My second solution:
class Solution { private int sum =0; public int sumNumbers(TreeNode root) { preOrder(root, 0); return sum; } private void preOrder(TreeNode root, int num){ if(root==null) return; if(root.left==null&&root.right==null){ sum+=num*10+root.val; return; } preOrder(root.left, num*10+root.val); preOrder(root.right, num*10+root.val); } }