1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { int ans = 0; public int sumNumbers(TreeNode root) { if(root == null){ return ans; } dfs(root, root.val); return ans; }
public void dfs(TreeNode root, int val){ if(root.left == null && root.right == null){ ans += val; return; } if(root.left != null){ dfs(root.left, val*10 + root.left.val); } if(root.right != null){ dfs(root.right, val*10 + root.right.val); } } }
|