leetcode-Day8

从零开始Leetcode – Day 8

Sum Root to Leaf Numbers

https://leetcode.com/problems/sum-root-to-leaf-numbers/
用private function 做, 这样子sum就在function里了。 leetcode OJ 不能全局变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

var sumNumbers = function(root) {
var sum = 0;
var path = 0;
helper(root, path);
return sum;

function helper(root, path){
if(!root){
return;
}

path = path * 10 + root.val;
if(!root.left && !root.right){
sum += path;
return sum;
}
if(root.left){
helper(root.left, path);
}
if(root.right){
helper(root.right, path);
}
}
};