题目,来自牛客网
法1:使用全局变量
public class Solution {public int res = 0;public int sumNumbers (TreeNode root) {if (root == null) {return 0;}dfs(root, 0);return res;}public void dfs(TreeNode root, int preSum) {if (root.left == null && root.right == null) {res += preSum * 10 + root.val;return;}int res = preSum * 10 + root.val;if (root.left != null) {dfs(root.left, res);}if (root.right != null) {dfs(root.right, res);}}
}
法2:不用全局变量
public class Solution {public int sumNumbers (TreeNode root) {if (root == null) {return 0;}return dfs(root, 0);}public int dfs(TreeNode root, int preSum) {if (root == null) {return 0;}if (root.left == null && root.right == null) {return preSum * 10 + root.val;}int curSum = preSum * 10 + root.val;return dfs(root.left, curSum) + dfs(root.right, curSum);}
}