二叉树的创建和遍历:
#include<stdio.h>
#include<stdlib.h>
struct TreeNode
{
int val ;
TreeNode* left;
TreeNode* right;
} ;
TreeNode* build_tree( ) ;
void show_imformation( TreeNode *root);
void find_x(TreeNode *root , int * max) ;
void find_max(TreeNode *root , int * max) ;
void find_min(TreeNode *root , int * max);
int main(void)
{
TreeNode *root,root2;
root2.val =NULL;
int a =0, b = -1;
int *max ,*min;
max = &a;
min = &b ;
root =build_tree( );
printf("创建树完成!\n") ;
show_imformation( root );
int n ;
printf("请输入您需要查找的树:\n");
scanf("%d" ,&n);
find_x( root, &n);
find_max(root ,max);
printf("\n最大值是:\n%d" ,*max);
find_min(root , min);
printf("\n最小值是:\n%d" ,*min);
return 0;
}
struct TreeNode* build_tree() {
int val;
scanf("%d" ,&val);
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode*));
if (val <= 0) {
return NULL;
}
if (!root) {
printf("创建失败\n");
return NULL;
}
if (val > 0) {
root->val = val;
printf("请输入%d的左节点", val);
root->left = build_tree();
printf("请输入%d的右节点", val);
root->right = build_tree();
}
return root;
}
void show_imformation( TreeNode *root)
{
if (root == NULL) {
return;
}
printf("%d " ,root->val) ;
show_imformation(root->left);
show_imformation(root->right);
}
void find_x(TreeNode *root , int * max)
{
if (root == NULL) {
return ;
}
if(*max == root->val)
{
printf("\n在树里\n%d" ,*max);
return;
}
find_x(root->left , max);
find_x(root->right , max);
return ;
}
void find_max(TreeNode *root , int * max)
{
if (root == NULL) {
return ;
}
if(*max < root->val)
{
*max = root->val ;
}
find_max(root->left , max);
find_max(root->right , max);
return ;
}
void find_min(TreeNode *root , int * max)
{
if (root == NULL) {
return ;
}
if(*max == -1)
{
*max = root->val ;
}
if(*max > root->val)
{
*max = root->val ;
}
find_min(root->left , max);
find_min(root->right , max);
return ;
}