数据结构与算法分析 p80 4.3二叉查找树 例程

数据结构与算法分析 p80 4.3二叉查找树 例程

#include<stdio.h>
#include<stdlib.h>

typedef struct treenode *position;
typedef struct treenode *searchtree;
struct treenode {
	int num;
	searchtree left;
	searchtree right;
};
searchtree makeempty(searchtree t) {
	if (t != NULL) {
		makeempty(t->left);
		makeempty(t->right);
		free(t);
	}
	return NULL;

}
position find(int x, searchtree t) {
	position k;
	if (t == NULL) {
		return NULL;
	}
	if (x < t->num) {
		k = find(x, t->left);
	}
	else if (x > t->num) {
		k = find(x, t->right);


	}
	else {
		k = t;
	}
	return k;
}
position findmin(searchtree t) {
	if (t->left != NULL) {
		return findmin(t->left);
	}
	else {
		return t;
	}
}
position findmax(searchtree t) {
	while (t->right != NULL) {
		t = t->right;
	}
	return t;
}
position insert(int x, searchtree t) {
	if (t == NULL) {
		t = (position)malloc(sizeof(struct treenode));
		t->num = x;
		t->left = NULL;
		t->right = NULL;
	}
	else {
		if (x > t->num) {
			t->right=insert(x, t->right);
		}
		else if (x < t->num) {
			t->left = insert(x, t->left);
		}
	}
	return t;
}
searchtree deletenode(int x, searchtree t) {
	position tmpcell;
	if (t == NULL) {
		printf("element not found");
	}
	else if(x < t->num) {
		t->left = deletenode(x, t->left);

	}
	else if (x > t->num) {
		t->right = deletenode(x, t->right);
	}
	else {
		if (t->left&&t->right) {
			tmpcell = findmin(t->right);
			t->num = tmpcell->num;
			deletenode(t->num,t->right);
		}
		else {
			tmpcell = t;
			t = NULL;
			if (t->left) {
				t = t->left;
			}
			if (t->right) {
				t = t->right;
			}
			free(tmpcell);
		}
	}
	return t;
}
void inorder(searchtree t) {
	if (t != NULL) {
		inorder(t->left);
		printf("%d", t->num);
		inorder(t->right);
	}
}
int main() {
	searchtree t=NULL;
	int a;
	for (int i = 0; i < 10; i++) {
		scanf("%d", &a);
		t=insert(a, t);
	}
	inorder(t);
	return 0;
}

在这里插入图片描述

发布了4 篇原创文章 · 获赞 0 · 访问量 52

猜你喜欢

转载自blog.csdn.net/qq_41687358/article/details/104098867