LeetCode_将LeetCode中的字符串用例转换成二叉树

最近刷LeetCode题目时总会出现错误时,手动生成用例的情况,于是自己写了一个将格式字串转换成二叉树的函数。

//实现将一个字符串转换成二叉树
//str的形式按照LeetCode上所描述str={1,#,2,3}

int getOneNodeVal(string &str,int &curPos){
    int rootVal=0;
    int nextPos=curPos;
    string valStr;
    //生成根节点
    nextPos=str.find_first_of(',',curPos);
    if (nextPos!=string::npos){
        valStr = str.substr(curPos,nextPos-curPos);
    }
    else{
       valStr = str.substr(curPos,str.size()-1-curPos);
    }
    rootVal = atoi(valStr.c_str());
    curPos=nextPos;
    return rootVal;
}

TreeNode * StringToBinaryTree(string str){
    //空树返回NULL
    if (str.compare("{}")==0){
        return NULL;
    }

    //生成根节点
    int rootVal=0;
    int curPos=1;
    rootVal = getOneNodeVal(str,curPos);
    TreeNode *root = new TreeNode(rootVal);

    //初始化广度优先队列
     vector <TreeNode *> preLevel,curLevel;
    preLevel.push_back(root);

    //遍历字符串生成二叉树
    int levelNodeNum=2; 
    int alreadyGenerate=0;
    TreeNode *pTemp=NULL;
    while(true){
        //证明所有节点都生成完毕了
        if (curPos==string::npos){
            break;
        }
        curPos++;
        if (str[curPos]=='#'){
            curPos++;pTemp=NULL;
        }
        else{
            rootVal = getOneNodeVal(str,curPos);
            TreeNode *pTemp = new TreeNode(rootVal);
            //left child
            if (alreadyGenerate%2==0){
                preLevel[alreadyGenerate/2]->left=pTemp;
            }
            //right child
            else{
                preLevel[alreadyGenerate/2]->right=pTemp;
            }
            curLevel.push_back(pTemp);
        }
        alreadyGenerate ++;
        if (alreadyGenerate==levelNodeNum)
        {
            alreadyGenerate=0;
            preLevel.swap(curLevel);
            curLevel.clear();
            levelNodeNum=preLevel.size()*2;
        }
    }
    return root;
}


你可能感兴趣的:(LeetCode)