Q129. Sum Root to Leaf Numbers
1
/ \
2 3分析
C++代码
/**
* 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 res = 0;
if(!root) return 0;
helper(root, root->val, res, 0);
return res;
}
private:
void helper(TreeNode* root, int path, int& res, int height){
if (!root->left && !root->right){
res += path;
return;
}else{
if(root->left) helper(root->left, 10 * path + root->left->val, res, height+1);
if(root->right) helper(root->right, 10 * path + root->right->val, res, height+1);
}
}
};PreviousQ117. Populating Next Right Pointers in Each Node IINextQ144. Binary Tree Preorder Traversal
Last updated