0%

129. Sum Root to Leaf Numbers

preorder O(n) time O(h) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root, int num = 0) {
return sum(root, 0);
}

private:
long sum(TreeNode *root, long val) { // 返回这棵树所有Root to Leaf Numbers的和
if (!root) return 0;
val = val * 10 + root->val;
if (!root->left && !root->right) return val; // 叶节点要单独处理
return sum(root->left, val) + sum(root->right, val);
}
};