二叉树遍历,插入数据,求树的高度,求二叉树中的最大值
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node* left; struct node* right; }Node; typedef struct tree { Node* root; }Tree; //二叉树插入数据模块 void Insert(Tree* tree, int value) { Node* node = (Node*)malloc(sizeof(Node)); node->data = 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->data) 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; } } } } //二叉树遍历模块 void prv(node* n) { if (n != NULL) { printf("%d\n", n->data); prv(n->left); prv(n->right); } } void mid(node* n) { if (n != NULL) { mid(n->left); printf("%d\n", n->data); mid(n->right); } } void behind(node* n) { if (n != NULL) { behind(n->left); behind(n->right); printf("%d\n", n->data); } } //二叉树求深度模块 int get_high(node* n) { if (n == NULL) return 0; else { int left = get_high(n->left); int right = get_high(n->right); int max = left; if (right > max) max = right; return max + 1; } } //二叉树求树中的最大值 int get_max(node* n) { if (n == NULL) return -1; else { int left_max = get_max(n->left); int right_max = get_max(n->right); int mine = n->data; int max = mine; if (left_max > mine) { max = left_max; } if (right_max > mine) { max = right_max; } return max; } } int main(void) { int a[7] = { 6,3,8,2,5,7,1 }; Tree t1; t1.root = NULL; for (int i = 0; i < 7; i++) { Insert(&t1, a[i]); } /*mid(t1.root);*/ int n =get_max(t1.root); printf("%d", n); }
计算机小白记录学习过程,喜欢就点个推荐和关注吧O(∩_∩)O哈哈~

浙公网安备 33010602011771号