最近学习的,关于二叉树的建立,前中后序遍历,和求二叉树高等。
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int date;
struct node* left;
struct node* right;
} Node;
typedef struct
{
Node* root;
} Tree;
void preorder(Node* node)//先(前)序遍历(根-左-右)
{
if(node != NULL)
{
printf("%d ",node -> date);
preorder(node -> left);
preorder(node -> right);
}
}
void inorder(Node* node)//中序遍历(左-根-右)
{
if(node != NULL)
{
inorder(node -> left);
printf("%d ",node -> date);
inorder(node -> right);
}
}
void postorder(Node* node)//后序遍历(左-右-根)
{
if(node != NULL)
{
postorder(node -> left);
postorder(node -> right);
printf("%d ",node -> date);
}
}
void insert(Tree* tree,int value)//二叉搜索树的建立
{
Node* node=(Node*)malloc(sizeof(Node));
node -> date = value;
node -> left = NULL;
node -> right = NULL;
if(tree -> root == NULL)
tree -> root = node;
else
{
Node* temp = tree -> root;
while(temp != NULL)
{
if(value < temp -> date)
{
if(temp -> left == NULL)
{
temp -> left = node;
return ;
}
else
temp = temp -> left;
}
else
{
if(temp -> right == NULL)
{
temp -> right = node;
return ;
}
else
temp = temp -> right;
}
}
}
}
int get_height(node* node)//递归求高
{
if(node == NULL)
return 0;
else
{
int left_h = get_height(node -> left);
int right_h = get_height(node -> right);
int maxx = left_h;
if(right_h > maxx)
maxx=right_h;
return maxx+1;
}
}
int get_max(Node* node)//递归求最大值
{
if(node == NULL)
return -1;
else
{
int m1=get_max(node -> left);
int m2=get_max(node -> right);
int m3=node -> date;
int maxx = m1;
if(m2>maxx)
maxx = m2;
if(m3>maxx)
maxx = m3;
return maxx;
}
}
int main()
{
int arr[7] = {6,3,8,2,5,1,7};
Tree tree;
tree.root=NULL;
for(int i=0; i<7; i++)
{
insert(&tree,arr[i]);
}
printf("先序遍历\n");
preorder(tree.root);
printf("\n");
printf("中序遍历\n");
inorder(tree.root);
printf("\n");
printf("后序遍历\n");
postorder(tree.root);
printf("\n");
printf("h = %d\n",get_height(tree.root));
printf("max = %d\n",get_max(tree.root));
return 0;
}