您的位置:首页 > 其它

LeetCode(129) Sum Root to Leaf Numbers

2015-08-07 19:48 537 查看
深度优先搜索,没什么好讲的,已经很熟练了。

[code]/**
 * 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:

    void dfs(TreeNode *root, string &path, vector<int> &pathNum) {

        if(root->left == NULL && root->right == NULL) {

            path += to_string(root->val);
            int tmp = stoi(path);
            pathNum.push_back(tmp);
            path.pop_back();
            return;

        }

        path += to_string(root->val);

        if(root->left != NULL)

            dfs(root->left, path, pathNum);

        if(root->right != NULL)

            dfs(root->right, path, pathNum);

        path.pop_back();

    }

    int sumNumbers(TreeNode* root) {

        if(root == NULL)

            return 0;

        vector<int> pathNum;
        string path;

        dfs(root, path, pathNum);

        int sum = 0;
        for(int i = 0; i < pathNum.size(); i++) {

            sum += pathNum[i];

        }

        return sum;

    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: