Operación de árbol binario C ++ - Experimento 5 de estructura de datos de la Universidad de Shandong

Contenido del experimento:
1. Ingrese una cadena transversal completa a nivel de árbol binario, cree este árbol binario, genere la cadena transversal de preorden del árbol binario, la cadena transversal de orden medio, la cadena transversal posterior al pedido, el número de nodos, la altura del árbol binario (cada uno arriba Un resultado se muestra en su propia línea).
2. Ingrese la secuencia de preorden y la secuencia de orden medio del árbol binario (cada elemento es diferente), cree este árbol binario y genere la secuencia posterior al pedido y el recorrido de nivel del árbol binario.

el código se muestra a continuación

#include<iostream>
#include"string"
#include <malloc.h>
#include <queue>
using namespace std;
int i = 0;
int j = 0;
int k = 0;
int m = 0;
struct BinaryTreeNode    
{
    
    
	char data;
	struct BinaryTreeNode * lchild;
	struct BinaryTreeNode * rchild;
};

void preOrder(BinaryTreeNode *treeroot,int len)   //前序遍历输出 
{
    
    
	if (treeroot != NULL)
	{
    
    
		if (i != len-1)
		{
    
    
			cout << treeroot->data <<',';
		i++;
		}
		else
		cout << treeroot->data;
		
		preOrder(treeroot->lchild,len);
		preOrder(treeroot->rchild,len);
	}
} 
void inOrder(BinaryTreeNode *treeroot,int len)    //中序遍历输出
{
    
    
	if (treeroot != NULL)
	{
    
    
		inOrder(treeroot->lchild,len);
		if (j != len-1)
		{
    
    
			cout << treeroot->data <<',';
			j++;
		}
		else
			cout << treeroot->data;
		inOrder(treeroot->rchild,len);
	}
}
void lastOrder(BinaryTreeNode *treeroot,int len)    //后序遍历输出
{
    
    
	if (treeroot != NULL)
	{
    
    
		lastOrder(treeroot->lchild,len);
		lastOrder(treeroot->rchild,len);
		if (k != len-1)
		{
    
    
			cout << treeroot->data <<',';
			k++;
		}
		else
			cout << treeroot->data;
	}
}

int hight (BinaryTreeNode *treeroot)       //求二叉树高度(递归实现) 
{
    
    
	if (treeroot == NULL)
		return 0;
	int hl = hight(treeroot->lchild);
	int hr = hight(treeroot->rchild);
	if (hl > hr)    //返回左右两个子树中高度最大的并加一 
		return ++hl;
	else
		return ++hr;
} 
 
BinaryTreeNode *ConstructBinaryTree(char * str, int len, int i)   //给出层序遍历str,节点个数len,根节点索引i 
																//构造完全二叉树并返回root 
{
    
    
	if (len < 1)
		return NULL;
	BinaryTreeNode *root = NULL;
	if (i < len)
	{
    
    
		root = new BinaryTreeNode();
		if (root == NULL)return NULL;
		root->data = str[i];
		root->lchild = ConstructBinaryTree(str, len, 2 * i + 1);  //递归构造左子树 
		root->rchild = ConstructBinaryTree(str, len, 2 * i + 2);  //递归构造右子树
	}
	return root;
}

//由中序遍历和前序遍历构造节点个数为len的完全二叉树,构造的树为T,调用时传入一棵空树T。 
void pre_mid_createBiTree(BinaryTreeNode * &T,char *prim,char *mid,int len)
{
    
    
    if(len==0)
    {
    
    
        T=NULL;
        return ;
    }
    char ch = prim[0];  //前序遍历数组的第一个值即为树的根节点 
    int index =0;
    while(mid[index]!=ch)   //在中序遍历数组中,找出根节点的索引位置 
    {
    
                           //在根节点左边的,即为左子树,右边的即为右子树 
        index++;
    }
    T=(BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
    T->data = ch;
    pre_mid_createBiTree(T->lchild,prim+1,mid,index);    //递归构造左子树 
    pre_mid_createBiTree(T->rchild,prim+index+1,mid+index+1,len-index-1);   //递归构造左子树
}

void levelorder(BinaryTreeNode *root,int len)   //层序遍历输出 
{
    
    
	if (!root) return;
	queue<BinaryTreeNode *> q; //层序遍历利用队列先进先出的特点 
	BinaryTreeNode * look;			
	q.push(root);    //先把根节点放入队列中 	

	while (!q.empty())  //只要队列不为空 
	{
    
    
		look = q.front();  //从队列里取出一个元素 
		if (m != len-1)    //这么输出完全为了题目要求 
		{
    
    
			cout << look->data <<',';
			m++;
		}
		else	
			cout << look->data;
		q.pop();   

		if (look->lchild)   //如果左孩子不为空,把左孩子放入队列中 
			q.push(look->lchild);	 

		if (look->rchild)	//如果右孩子不为空,把右孩子放入队列中
			q.push(look->rchild);
	}
	cout << endl;
 } 

int main()
{
    
    
	BinaryTreeNode *t;
	char *input= new char [100];  //用来存放用户输入的层序遍历字符 
	string instr;
	cout << "Input1" << endl;
	cin >> instr; 
	for (int i = 0; i < instr.length(); i++)   //这一步好像写麻烦了,直接用instr不知道为啥不行 
	{
    
    
		input[i] = instr[i];
	}
	
	t = ConstructBinaryTree(input, instr.length(), 0);  
	cout << "Output1" << endl;
	preOrder(t,instr.length());
	cout <<endl;
	inOrder(t,instr.length());
	cout <<endl;
	lastOrder(t,instr.length());
	cout <<endl;
	
	cout << instr.length() <<endl;
	int h = hight(t);
	cout << h <<endl;
		
	char *preorder= new char [100];   //前序遍历字符数组 
	string instr1;
	cout << "Input2" << endl;
	cin >> instr1; 
	for (int i = 0; i < instr1.length(); i++)
	{
    
    
		preorder[i] = instr1[i];
	}	
	char *inorder= new char [100];   //中序遍历字符数组 
	string instr2;
	cin >> instr2; 
	for (int i = 0; i < instr2.length(); i++)
	{
    
    
		inorder[i] = instr2[i];
	}
		
    BinaryTreeNode * T;
    int n = instr1.length();
    
    pre_mid_createBiTree(T,preorder,inorder,n);
    cout << "Output2" << endl;
    
	lastOrder(T,n+instr.length()-1);
	cout <<endl;
	
	levelorder(T,n);
	cout << "End0";	
	return 0;
}

En el experimento adicional, el requisito de generar un árbol binario completo a partir del pedido anticipado y el orden medio se cambió por el de generar un árbol binario completo a partir del pedido posterior y el orden medio. La idea es la misma. Pegue el código de esta función a continuación y simplemente reemplácela directamente.

void last_mid_createBiTree(BinaryTreeNode * &T,char *last,char *mid,int len)
{
    
    
    if(len==0)
    {
    
    
        T=NULL;
        return ;
    }
    char ch = last[len-1];
    int index =0;
    while(mid[index]!=ch)
    {
    
    
        index++;
    }
    T=(BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
    T->data = ch;
    last_mid_createBiTree(T->lchild,last,mid,index);
    last_mid_createBiTree(T->rchild,last+index,mid+index+1,len-index-1);
}

Supongo que te gusta

Origin blog.csdn.net/m0_47470899/article/details/109727308
Recomendado
Clasificación