|
| 1 | +## 题目地址 |
| 2 | + |
| 3 | +https://leetcode.com/problems/sum-root-to-leaf-numbers/description/ |
| 4 | + |
| 5 | +## 题目描述 |
| 6 | + |
| 7 | +``` |
| 8 | +Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. |
| 9 | +
|
| 10 | +An example is the root-to-leaf path 1->2->3 which represents the number 123. |
| 11 | +
|
| 12 | +Find the total sum of all root-to-leaf numbers. |
| 13 | +
|
| 14 | +Note: A leaf is a node with no children. |
| 15 | +
|
| 16 | +Example: |
| 17 | +
|
| 18 | +Input: [1,2,3] |
| 19 | + 1 |
| 20 | + / \ |
| 21 | + 2 3 |
| 22 | +Output: 25 |
| 23 | +Explanation: |
| 24 | +The root-to-leaf path 1->2 represents the number 12. |
| 25 | +The root-to-leaf path 1->3 represents the number 13. |
| 26 | +Therefore, sum = 12 + 13 = 25. |
| 27 | +Example 2: |
| 28 | +
|
| 29 | +Input: [4,9,0,5,1] |
| 30 | + 4 |
| 31 | + / \ |
| 32 | + 9 0 |
| 33 | + / \ |
| 34 | +5 1 |
| 35 | +Output: 1026 |
| 36 | +Explanation: |
| 37 | +The root-to-leaf path 4->9->5 represents the number 495. |
| 38 | +The root-to-leaf path 4->9->1 represents the number 491. |
| 39 | +The root-to-leaf path 4->0 represents the number 40. |
| 40 | +Therefore, sum = 495 + 491 + 40 = 1026. |
| 41 | +
|
| 42 | +``` |
| 43 | + |
| 44 | +## 思路 |
| 45 | + |
| 46 | +这是一道非常适合训练递归的题目。虽然题目不难,但是要想一次写正确,并且代码要足够优雅却不是很容易。 |
| 47 | + |
| 48 | +这里我们的思路是定一个递归的helper函数,用来帮助我们完成递归操作。 |
| 49 | +递归函数的功能是将它的左右子树相加,注意这里不包括这个节点本身,否则会多加, |
| 50 | +我们其实关注的就是叶子节点的值,然后通过层层回溯到root,返回即可。 |
| 51 | + |
| 52 | +整个过程如图所示: |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +那么数字具体的计算逻辑,如图所示,相信大家通过这个不难发现规律: |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +## 关键点解析 |
| 62 | + |
| 63 | +- 递归分析 |
| 64 | + |
| 65 | +## 代码 |
| 66 | + |
| 67 | +```js |
| 68 | +/* |
| 69 | + * @lc app=leetcode id=129 lang=javascript |
| 70 | + * |
| 71 | + * [129] Sum Root to Leaf Numbers |
| 72 | + */ |
| 73 | +function helper(node, cur) { |
| 74 | + if (node === null) return 0; |
| 75 | + const next = node.val + cur * 10; |
| 76 | + |
| 77 | + if (node.left === null && node.right === null) return next; |
| 78 | + |
| 79 | + const l = helper(node.left, next); |
| 80 | + const r = helper(node.right, next); |
| 81 | + |
| 82 | + return l + r; |
| 83 | +} |
| 84 | +/** |
| 85 | + * Definition for a binary tree node. |
| 86 | + * function TreeNode(val) { |
| 87 | + * this.val = val; |
| 88 | + * this.left = this.right = null; |
| 89 | + * } |
| 90 | + */ |
| 91 | +/** |
| 92 | + * @param {TreeNode} root |
| 93 | + * @return {number} |
| 94 | + */ |
| 95 | +var sumNumbers = function(root) { |
| 96 | + // tag: `tree` `dfs` `math` |
| 97 | + return helper(root, 0); |
| 98 | +}; |
| 99 | +``` |
| 100 | + |
| 101 | +## 相关题目 |
| 102 | + |
| 103 | +- [sum-of-root-to-leaf-binary-numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/) |
| 104 | + |
| 105 | +> 这道题和本题太像了,跟一道题没啥区别 |
| 106 | +
|
0 commit comments