从零开始Leetcode – Day 7
Sum Root to Leaf Numbers
https://leetcode.com/problems/sum-root-to-leaf-numbers/
把sum变成了array(object), 然后再pass by reference. primitive type 是pass by value.
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 26 27 28 29 30 31 32 33 34 35 36 37
| /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ var sumNumbers = function(root) { var sum = {sum:0}; var path = 0; helper(root, sum, path); return sum.sum; };
var helper = function(root, sum, path){ if( return; } path = path * 10 + root.val; if( sum.sum += path; return sum; } if(root.left){ helper(root.left, sum, path); } if(root.right){ helper(root.right, sum, path); } };
|