二刷
100.00
class Solution {
public int sumNumbers(TreeNode root) {
int[] sum = new int[1];
if (root != null) {
helper(root, root.val, sum);
}
return sum[0];
}
private void helper(TreeNode node, int num, int[] sum) {
if (node.left == null && node.right == null) {
sum[0] += num;
} else {
if (node.left != null) {
helper(node.left, num * 10 + node.left.val, sum);
}
if (node.right != null) {
helper(node.right, num * 10 + node.right.val, sum);
}
}
}
}
一刷
25.08 %
public class Solution {
private int sum;
public int sumNumbers(TreeNode root) {
sum = 0;
//TODO
sumNumbersHelper(root, 0);
return sum;
}
private void sumNumbersHelper(TreeNode root, int path) {
if (root == null) return;
path = path * 10 + root.val;
//leaf node
if (root.left == null && root.right == null) {
sum += path;
return;
}
//go to the next layer
sumNumbersHelper(root.left, path);
sumNumbersHelper(root.right, path);
}
}
No comments:
Post a Comment