二叉树前中后序遍历
#include<cstdio>
#include<cstdlib>
typedef struct node{
int data;
struct node* left;
struct node* right;
}Node;
void preorder(Node* root){
if(root == NULL) return;
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(Node* root){
if(root == NULL) return;
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
void postorder(Node* root){
if(root == NULL) return ;
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
int main(){
Node n1;
Node n2;
Node n3;
Node n4;
n1.data = 5;
n2.data = 6;
n3.data = 7;
n4.data = 8;
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = NULL;
n3.left = NULL;
n3.right = NULL;
n4.left = NULL;
n4.right = NULL;
preorder(&n1);
putchar(10);
inorder(&n1);
putchar(10);
postorder(&n1);
return 0;
}
二叉搜索树的高度和最值
#include<cstdio>
#include<cstdlib>
typedef struct node{
int data;
struct node* left;
struct node* right;
}Node;
typedef struct{
Node* root;
}Tree;
void preorder(Node* root){
if(root == NULL) return;
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(Node* root){
if(root == NULL) return;
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
void postorder(Node* root){
if(root == NULL) return ;
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
int max(int a, int b){
return a>b?a:b;
}
int get_height(Node* node){
if(node == NULL) return 0;
return max(get_height(node->left), get_height(node->right)) + 1;
}
int get_maximum(Node* node){
if(node == NULL){
return -1;
}
int maxl = get_maximum(node->left);
int maxr = get_maximum(node->right);
int maxc = node->data;
if(maxl > maxc) maxc = maxl;
if(maxr > maxc) maxc = maxr;
return maxc;
}
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(temp->data > value){
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 main(){
int arr[]={6,3,8,2,5,1,7};
Tree tree;
tree.root = NULL;
for(int i=0;i<7;i++){
insert(&tree, arr[i]);
}
preorder(tree.root);
putchar(10);
inorder(tree.root);
putchar(10);
postorder(tree.root);
putchar(10);
int h = get_height(tree.root);
printf("h = %d\n",h);
int mx = get_maximum(tree.root);
printf("max = %d\n",mx);
return 0;
}