先序,中序建立二叉樹

由二叉樹的先序和中序序列建立二叉樹
非常經典的算法,先序序列確定根,中序序列確定左右子樹,遞歸即可。

TreeNode* Tree:: BuildTree(string &Pre, string &In,string d){
    //cout <<d<< "=======================================" << endl;
    //cout <<d<< "Pre=" << Pre << ",In=" << In << endl;
    if (Pre.size() == 0 || In.size() == 0){
        return nullptr;
    }else{
        TreeNode *cur=new TreeNode(Pre[0]);
        cout <<d<< "create node " << Pre[0] << endl;
        int rooti = In.find(Pre[0]);
        d += "    ";
        cur->left=BuildTree(Pre.substr(1,rooti ), In.substr(0, rooti),d);
        cur->right=BuildTree(Pre.substr(rooti + 1, Pre.size()), In.substr(rooti + 1, In.size()),d);
        return cur;
    }
}

BuildTree(string(“ABDEHJKLMNCFGI”),string(“DBJHLKMNEAFCGI”),” “);
上面序列建成的樹形狀如圖:
這裏寫圖片描述
二叉樹打印見:
http://blog.csdn.net/u010909667/article/details/54972495

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章