1. 程式人生 > >LeetCode - Contruct Binary Tree from String

LeetCode - Contruct Binary Tree from String

解法一:recursion

class Solution {
public:
    TreeNode* str2tree(string s) {
        if(s.empty()) return nullptr;
        auto found = s.find('(');
        TreeNode* root;
        if(found==string::npos) return new TreeNode(stoi(s));
        else root = new TreeNode(stoi(s.substr(0, found)));
        int l=0;
        int i;
        for(i=found;i<s.size();i++){
            if(s[i]=='(') l++;
            else if(s[i]==')') l--;
            if(l==0) break;
        }
        root->left = str2tree(s.substr(found+1, i-found-1)); //i-1-(found+1)+1
        found = s.find('(', i+1);
        if(found==string::npos) return root;
        else root->right = str2tree(s.substr(found+1, s.size()-found-1)); //s.size()-1-(found+1)+1
        return root;
    }
};