5_26打卡_二叉树的创建与遍历(递归)

发布时间 2023-05-27 18:08:12作者: aallofitisst
#include<iostream>
using namespace std;

typedef struct tree {
	char data;
	tree* lchild;
	tree* rchild;
}tree;


//递归实现创建树
void creatTree(tree*& root)
{
	char ch;
	cin >> ch;
	if (ch == '0')
	{
		root = NULL;
	}
	else {
		root = new tree;
		root->data = ch;
		creatTree(root->lchild);
		creatTree(root->rchild);
	}
}


//递归  前遍历
void print_tree(tree* root)
{
	if (root == NULL)
	{
		return;
	}
	else {
		cout << root->data;
		print_tree(root->lchild);
		print_tree(root->rchild);
	}
}

int main()
{
	tree* root;
	creatTree(root);
	print_tree(root);
	return 0;
}