1、先序+中序
node* create(int preL, int preR, int inL, int inR){
if(preL > preR){
return NULL;
}
node* root = new node;
root->data = pre[preL];
int k;
for(k = inL; k <= inR; k++){
if(in[k] == pre[preL]){
break;
}
}
int numLeft = k - inL;
root->lchild = create(preL+1, preL+numLeft, inL, k-1);
root->rchild = create(preL+numLeft+1,preR,k+1,inR);
return root;
}
2、后序+中序
node* create(int postL, int postR, int inL, int inR){
if(postR - postL < 0)
return NULL;
node* root = new node;
root->data = post[postR];
int k;
for(k = inL; k <= inR; k++){
if(in[k] == post[postR])
break;
}
int numLeft = k - inL;
root->lchild = create(postL,postL+numLeft-1,inL,k-1);
root->rchild = create(numLeft+postL, postR-1, k+1, inR);
return root;
}
3、先序遍历
void preorder(node* root){
if(root == NULL){
return;
}
printf("%d\n", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
4、中序遍历
void inorder(node* root){
if(root == NULL) return;
inorder(root->lchild);
printf("%d\n",root->data);
inorder(root->rchild);
}
5、后序遍历
void postorder(node* root){
if(root == NULL) return ;
postorder(root->lchild);
postorder(root->rchild);
printf("%d\n",root->data);
}
6、层序遍历
void LayerOrder(node* root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* now = q.front();
q.pop();
if(now->lchild != NULL) q.push(now->lchild);
if(now->rchild != NULL) q.push(now->rchild);
}
}