辉哥带我学数据结构】二叉树(二)通过[中序、先序、后序、层序]建立二叉树

/**
	已知二叉树序列建立二叉树:
		已知一种遍历结果
			层序
			先序
			中序
			后序
		已知两种遍历结果
			中+先
			中+后
			先+后 
	author:mmciel
	time:2019-4-4 09:07:18 
*/
#include<bits/stdc++.h>
using namespace std; 


//类型一:已知一种遍历结果且含虚空节点的建立方案
/*三种
层序:方法:如果两个子节点除以二等于父节点 
先序:code1
后序:略(同code1) 
中序:不可行!
*/

typedef struct bnode{
	char data;
	struct bnode *Lchild;
	struct bnode *Rchild;
}BiNode,*BiTree;
string s;
char t;
int k=0;


//code1
void create_tree(BiTree &T){
	if(k<s.size()) t = s[k++];
	
	if(t == '#'){
		T = NULL;
		return;
	}
	
	//T = (BiNode *)malloc(sizeof(BiNode));
	T = (BiTree)malloc(sizeof(BiNode));
	T->Lchild = NULL;
	T->Rchild = NULL;
	
	//这里顺序不能改变,否则当前结点无法获得t的值
	T->data = t;
	create_tree(T->Lchild);
	create_tree(T->Rchild);
	return;
}
int main(){
	cin>>s;//abc##de#g##f###
	BiTree T=NULL;
	create_tree(T);
	return 0;
} 
//类型二:已知多种遍历,建立二叉树
/*
通过中序遍历和先序遍历可以确定一个树。 
通过中序遍历和后续遍历可以确定一个树。
通过先序遍历和后序遍历确定不了一个树。

解:中序加先序code2:
1、通过先序遍历找到根结点A,再通过A在中序遍历的位置找出左子树,右子树
2、在A的左子树中,找左子树的根结点(在先序中找),转步骤1
3、在A的右子树中,找右子树的根结点(在先序中找),转步骤1
  
*/
//code2:
typedef struct bnode{
	char data;
	struct bnode *Lchild;
	struct bnode *Rchild;
}BiNode,*BiTree;

char treehead[]={"abc"};//先序 
char treecenter[]={"cab"};//中序 
int len = strlen(treecenter);//中序遍历中,根左右的长度 
BiTree creattree(char treehead[],char treecenter[],int len){
	int i=0;
	if(len == 0){//中序没了,完成 
		return NULL;
	}
	for(i=0;i<len;i++){
		if(treehead[i] == *treecenter ) break;
	} 
	BiTree t=(BiTree)malloc(sizeof(BiNode));
	
	t->data=*treecenter;
    t->Lchild=creattree(treecenter+1,treehead,i);
	//在先序序列中按顺序执行,中序起始位置不变,
	//循环长度为左边孩子长度,即为i
    t->Rchild=creattree(treecenter+i+1,treehead+i+1,len-i-1);
	//先序循环和中序循环要跳过根左孩子长度然后再跳过根,
	 //长度要保留到根右孩子长度,即为len-i-1
    return  t;
} 
int main()
{
	BiTree T = NULL;
	T=creattree(treehead,treecenter,len);
	return 0;
}
//二叉树遍历

void print_head(BiTree &T){
	if(T==NULL) {
		return ;
	}
	
	cout<<(T->data)<<" ";
	print_head(T->Lchild);
	print_head(T->Rchild);
}
void print_center(BiTree &T){
	if(T==NULL) {
		return ;
	}
	
	print_center(T->Lchild);
	cout<<(T->data)<<" ";
	print_center(T->Rchild);
} 
void print_eend(BiTree &T){
	if(T==NULL) {
		return ;
	}
	
	print_eend(T->Lchild);
	print_eend(T->Rchild);
	cout<<(T->data)<<" ";
} 

猜你喜欢

转载自blog.csdn.net/F_zmmfs/article/details/89010856