[LeetCode]Sum Root to Leaf Numbers

来源:互联网 发布:在淘宝上开网店要钱吗 编辑:程序博客网 时间:2024/04/29 00:59
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 togethervoid 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 overans += 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() functionint 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;    }};


原创粉丝点击