mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 129. Sum Root to Leaf Numbers.md
This commit is contained in:
parent
12f1119872
commit
008a8234cf
24
solutions/129. Sum Root to Leaf Numbers.md
Normal file
24
solutions/129. Sum Root to Leaf Numbers.md
Normal file
@ -0,0 +1,24 @@
|
||||
# [129. Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)
|
||||
# 思路
|
||||
采用递归的思路:用sum记录根到某节点组成数字的值,那么每遇到一个子结点的数字,要把之前sum的数字扩大10倍之后再加上当前节点的值。
|
||||
如果遍历到叶结点了,就将当前的累加结果sum返回。如果不是,则对其左右子结点分别调用递归函数,将两个结果相加返回即可。
|
||||
|
||||
当然也可以改成非递归的,可以用当前节点的val记录上述的sum:将自己的val加上父节点的val乘10作为新的val,例如`node->left->val += 10 * node->val`,代码这里
|
||||
就不放了。
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
private:
|
||||
int helper(TreeNode* root, int sum){
|
||||
if(!root) return 0;
|
||||
sum = sum * 10 + root -> val;
|
||||
if(!root -> left && !root -> right) return sum;
|
||||
return helper(root -> left, sum) + helper(root -> right, sum);
|
||||
}
|
||||
public:
|
||||
int sumNumbers(TreeNode* root) {
|
||||
return helper(root, 0);
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user