由二叉樹的先序和中序序列建立二叉樹
非常經典的算法,先序序列確定根,中序序列確定左右子樹,遞歸即可。
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