https://blog.csdn.net/Ajay666/article/details/76736333
BiNode * BiTree::create(string &s,int &pos){
++pos;
BiNode * t;
if((unsigned)pos>=s.size())
return NULL;
else{
if(s[pos]=='#')
t=NULL;
else{
t=new BiNode;
t->data=s[pos];
t->lchild=create(s,pos);
t->rchild=create(s,pos);
}
return t;
}
}
///按照前序遍历序列创建二叉树
void BiTree::createBiTree(string s){
int pos = -1;
root=create(s,pos);
}
---------------------
作者:Ajay666
来源:CSDN
原文:https://blog.csdn.net/Ajay666/article/details/76736333
版权声明:本文为博主原创文章,转载请附上博文链接!
这段代码生成的二叉树如下图:
我觉得代码的逻辑如下:
- 每次总是优先生成左子树
- 左子树满了(为NULL)则开始生成右子树
- 代码实现就是 t->lchild=create(s,pos); t->rchild=create(s,pos);右子树放左子树后面。注意每次调用左子树都会让树向下长大一些。