c语言-二叉树
2020-04-26 本文已影响0人
遇银
#include <stdio.h>
#include <stdlib.h>
typedef struct binary_tree
{
int data;
struct binary_tree *left;
struct binary_tree *right;
}node;
//插入节点
void insert(node **tree,int val)
{
node *temp = NULL;
if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left =temp->right =NULL;
temp->data = val;
*tree = temp;
return ;
}
if(val<(*tree)->data)
{
insert(&(*tree)->left,val);
}
else
{
insert(&(*tree)->right,val);
}
}
//回收资源
void deltree(node *tree)
{
if(tree)
{
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}
//先序
void print_preorder(node *tree)
{
if(tree)
{
printf("%d\n",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
//中序
void print_inorder(node *tree)
{
if(tree)
{
print_inorder(tree->left);
printf("%d\n",tree->data);
print_inorder(tree->right);
}
}
//后序
void print_postorder(node *tree)
{
if(tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n",tree->data);
}
}
int _max(int a, int b)
{
return a>b?a:b;
}
//最大深度
int maxDepth(node *tree)
{
if(tree == NULL)
{
return 0;
}
return 1+ _max(maxDepth(tree->left),maxDepth(tree->right));
}
//test
int main(void)
{
node *root;
root = NULL;
insert(&root,9);
insert(&root,4);
insert(&root,15);
insert(&root,6);
insert(&root,12);
insert(&root,17);
insert(&root,2);
printf("Pre Order Didplay\n");
print_preorder(root);
printf("In Order Display\n");
print_inorder(root);
printf("Post Order Display\n");
print_postorder(root);
printf("maxdepth= %d\n",maxDepth(root));
deltree(root);
}
运行结果:
wa@ubuntu:~$ gcc tree.c -o tree
wa@ubuntu:~$
wa@ubuntu:~$
wa@ubuntu:~$ ./tree
Pre Order Didplay
9
4
2
6
15
12
17
In Order Display
2
4
6
9
12
15
17
Post Order Display
2
6
4
12
17
15
9
maxdepth= 3