本文共 1575 字,大约阅读时间需要 5 分钟。
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: //recursive to find every path and then sum these path together void SumRecursive( TreeNode * root, int prev, int& ans ) { if(root == NULL) return; prev = prev*10+root->val; if (root->left == NULL && root->right == NULL) {//one path is over ans += prev; return; } SumRecursive(root->left, prev, ans); SumRecursive(root->right, prev, ans); } int sumNumbers(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function int ans = 0; SumRecursive(root, 0, ans); return ans; }};
second time
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void sumNumbersUtil(TreeNode* root, int curSum, int& totalSum) { curSum = curSum*10+root->val; if(root->left == NULL && root->right == NULL) { totalSum += curSum; return ; } if(root->left != NULL) sumNumbersUtil(root->left, curSum, totalSum); if(root->right != NULL) sumNumbersUtil(root->right, curSum, totalSum); } int sumNumbers(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) return 0; int totalSum = 0; int curSum = 0; sumNumbersUtil(root, curSum, totalSum); return totalSum; }};
转载地址:http://whxti.baihongyu.com/