根据先序和中序创建二叉树

在这里插入图片描述

#include <iostream>
using namespace std;


//链式存储 
struct BTNode{
	char data;
	BTNode *lchild;//左子树 
	BTNode *rchild;//右子树 
};
//创建二叉树
BTNode* CBT(string pre,string in){
	BTNode* T = new BTNode; //树根 
	if(pre.length() == 0){//先序序列长度为0,为NULL 
		T = NULL;
	}else{
		char r = pre[0];//先序序列的第一个结点为根结点
		T->data = r;
		
		//取出中序序列的左子树和右子树
		int index = in.find(r);//在中序序列中找到根节点下标,其下标就是左子树的长度
		string l_in = in.substr(0,index);//中序序列中截取左子树
		string r_in = in.substr(index+1);//中序序列中截取右子树
		//出去先序序列的左子树和右子树 
		string l_pre = pre.substr(1,index);//先序序列中截取左子树,从1开始是因为下标0是根节点,index也可以是r_pre.length()
		string r_pre = pre.substr(index+1);//先序序列中截取右子树
				
		T->lchild = CBT(l_pre,l_in);//创建左子树  传入先序左子树和中序左子树 
		T->rchild = CBT(r_pre,r_in);//创建右子树  传入先序右子树和中序右子树 
	}
	return T;
}
//先序遍历 
void po(BTNode* T){
	if(T!=NULL){
		cout<<T->data<<" ";
		po(T->lchild);
		po(T->rchild);
	}
}
//中序遍历
void po2(BTNode* T){
	if(T!=NULL){
		po2(T->lchild);
		cout<<T->data<<" ";
		po2(T->rchild);
	}
} 

int main(){
	
	string preorder = "ABDC";
	string inorder = "DBAC";
	
	BTNode* T = CBT(preorder,inorder);//create binary tree 创建二叉树
	
	po(T); //先序遍历 
	cout<<endl;
	po2(T); //中序遍历 

	return 0;
}

在这里插入图片描述

发布了167 篇原创文章 · 获赞 52 · 访问量 6923

猜你喜欢

转载自blog.csdn.net/qq_42363032/article/details/103914620