前序递归生成,前中后序遍历
#include<cstdio>
#include<cstdlib>
#include<string>
#include<iostream>
#include<cstdio>
using namespace std;
struct tree
{
int a;
tree *right;
tree *left;
} ;
//前序遍历生成二叉树
tree *start_preorder()
{
int c;
tree *b;
scanf("%d", &c);
if (c== 10)
{
b = NULL;
return NULL;
}
else
{
b = (tree*)malloc(sizeof(tree));
b->a = c;//数据写入
b->left=start_preorder();//加上左子树的节点个数,以及访问左子树节点数据
b->right=start_preorder();//加上右子树节点个数,以及访问右子树节点数据
return b;//返回当前根作为一棵树的节点数
}
}
//前序遍历打印二叉树
int print_preorder(tree *root)
{
if (root == NULL) return 0;
int k = 1;//k为当前根作为一棵树的节点数==1+左子树节点数+右子树节点个数
printf("%d", root->a);//访问数据
k+=print_preorder(root->left);//加上左子树的节点个数,以及访问左子树节点数据
k+=print_preorder(root->right);//加上右子树节点个数,以及访问右子树节点数据
return k;//返回当前根作为一棵树的节点数
}
//中序遍历打印二叉树
int print_inorder(tree *root)
{
if (root == NULL) return 0;
int k = 1;//k为当前根作为一棵树的节点数==1+左子树节点数+右子树节点个数
k += print_inorder(root->left);
printf("%d", root->a);
k += print_inorder(root->right);
return k;//返回当前根作为一棵树的节点数
}
//后序遍历打印二叉树
int print_postorder(tree *root)
{
if (root == NULL) return 0;
int k = 1;//k为当前根作为一棵树的节点数==1+左子树节点数+右子树节点个数
k += print_postorder(root->left);
k += print_postorder(root->right);
printf("%d", root->a);
return k;//返回当前根作为一棵树的节点数
}
int main()
{
tree a;
a=*start_inorder();
print_preorder(&a);
printf("\n");
print_inorder(&a);
printf("\n");
print_postorder(&a);
return 0;
}