#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node
{
int val;
struct Node* left;
struct Node* right;
}Node;
typedef struct Tree
{
Node* root;
int len;
}Tree;
Node* initNode(int val)
{
Node* n = (Node*)malloc(sizeof(Node));
n->val = val;
n->right = NULL;
n->left = NULL;
return n;
}
void freeNode(Node* n)
{
if (!n) return;
free(n);
return;
}
Tree* initTree()
{
Tree* t = (Tree*)malloc(sizeof(Tree));
t->root = NULL;
t->len = 0;
return t;
}
//Node* insertNode(Node* root,int val)
//{
// if (!root)
// {
// Node* n = initNode(val);
// return n;
// }
// if (val > root->val)
// root->right=insertNode(root->right, val);
// else
// root->left = insertNode(root->left, val);
// return root;
//}
void insertNode(Node** addr, int val)
{
if (!(*addr))
{
*addr= initNode(val);
return;
}
if (val > (*addr)->val)
insertNode(&((*addr)->right), val);
else
insertNode(&((*addr)->left), val);
return;
}
void insertTree(Tree* t, int val)
{
if (!t) return;
insertNode(&(t->root), val);
t->len++;
}
void preOrderTrav(Node* root)
{
if (!root) return;
printf("%d,", root->val);
preOrderTrav(root->left);
preOrderTrav(root->right);
return;
}
void inOrderTrav(Node* root)
{
if (!root) return;
inOrderTrav(root->left);
printf("%d,", root->val);
inOrderTrav(root->right);
return;
}
void postOrderTrav(Node* root)
{
if (!root) return;
postOrderTrav(root->left);
postOrderTrav(root->right);
printf("%d,", root->val);
return;
}
void freeAll(Node* root)
{
if (!root) return;
freeAll(root->left);
freeAll(root->right);
freeNode(root);
}
void preOrderTree(Tree* t)
{
if (!t) return;
printf("Pre :[");
preOrderTrav(t->root);
printf("]\n");
}
void inOrderTree(Tree* t)
{
if (!t) return;
printf("in :[");
inOrderTrav(t->root);
printf("]\n");
}
void postOrderTree(Tree* t)
{
if (!t) return;
printf("post:[");
postOrderTrav(t->root);
printf("]\n");
}
void outputTableNode(Node *root)
{
if (!root) return;
printf("%d", root->val);
if (!root->left && !root->right) return;
printf("(");
outputTableNode(root->left);
printf(",");
outputTableNode(root->right);
printf(")");
return;
}
void outputTableTree(Tree* t)
{
if (!t) return;
printf("Table:[");
outputTableNode(t->root);
printf("]\n");
return;
}
Node* findNode(Node* root, int val)
{
if (!root) return NULL;
if (val == root->val) return root;
if (val > root->val) return findNode(root->right,val);
else return findNode(root->left,val);
}
Node* findTree(Tree* t, int val)
{
if (!t) return NULL;
return findNode(t->root,val);
}
void freeTree(Tree* t)
{
if (!t) return;
freeAll(t->root);
free(t);
return;
}
int main()
{
srand(time(0));
Tree* t = initTree();
int cnt = 10;
while (cnt--)
{
int val = rand() % 100;
insertTree(t, val);
}
preOrderTree(t);
inOrderTree(t);
postOrderTree(t);
outputTableTree(t);
freeTree(t);
return 0;
}
09-29
2124
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交