由二叉树的先序和中序序列建立二叉树
非常经典的算法,先序序列确定根,中序序列确定左右子树,递归即可。
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.youkuaiyun.com/u010909667/article/details/54972495