欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构——递归实现二叉树

程序员文章站 2022-06-07 07:54:45
...

构造二叉树

typedef struct treenode
{
	TREE_TYPE data;
	struct treenode* left;/*指向左孩子*/
	struct treenode* right;/*指向右孩子*/

}Tree;

全部代码

#include<stdio.h>
#include<malloc.h>
typedef char TREE_TYPE;
typedef struct treenode
{
	TREE_TYPE data;
	struct treenode* left;/*指向左孩子*/
	struct treenode* right;/*指向左孩子*/

}Tree;
Tree* Create_Tree(Tree*&root)
{
	char ch;
	scanf_s("%c", &ch);
	if (ch == '#')/*出口*/
		root = NULL;
	else
	{
		root = (Tree*)malloc(sizeof(Tree));
		root->data = ch;
		root->left = Create_Tree(root->left);/*先创建左子树*/
		root->right = Create_Tree(root->right);/*在创建右子树*/

	}
	return root;

}
void Pre_order(Tree*&root)
{
	if (root)/*当root 指针不为空时*/
	{
		printf("%c\t", root->data);
		Pre_order(root->left);
		Pre_order(root->right);

	}


}
void Middle_order(Tree*&root)
{
	if (root)
	{
	    	Middle_order(root->left);
			printf("%c\t", root->data);
			Middle_order(root->right);
	}
}
void Back_order(Tree*& root)
{
	if (root)
	{
		Back_order(root->left);
		Back_order(root->right);
		printf("%c\t", root->data);
	}
}
int main(void)
{
	Tree* root = NULL;
	puts("Enter the node:");
	 Create_Tree(root);
	puts("The first order traversal:");
	Pre_order(root);
	puts("\nThe Middle order tracersal:");
	Middle_order(root);
	puts("\nThe back order is:");
	Back_order(root);

}

数据结构——递归实现二叉树
数据结构——递归实现二叉树