1,编写程序,从键盘输入10个整数,逐个插入到二叉排序树中。根据你输入的整数序列,在草稿纸上画出该树。

(1)分别用先序、中序、后序遍历该树并输出结果,检查结果是否正确。
(2)输出该树的高度,检查结果是否正确。
(3)输出结点总数,检查结果是否正确。
(4)从树中删除一个整数,遍历该树并输出,检查结果是否正确。

#include
#include 
struct TreeNode { 
    int Data;
    int Height;
    struct TreeNode * Left;
    struct TreeNode * Right;
};
struct TreeNode*Insert(struct TreeNode*T,int x){
	if(T==NULL){
		T=(struct TreeNode*)malloc(sizeof(struct TreeNode));
		T->Data=x;
		T->Height=0;
		T->Left=NULL;
		T->Right=NULL;
	}else if(x<T->Data){
		T->Left=Insert(T->Left,x);
	}else{
		T->Right=Insert(T->Right,x);
	}
	return T;	
}
int Max(int a,int b){
	return a>b?a:b;
}
int Height(struct TreeNode*T){
	if(T==NULL){
		return 0;
	}
	else{
		return 1+Max(Height(T->Left),Height(T->Right));
	}
}
void PreOrder(struct TreeNode*T){
	if(T!=NULL){
		printf("%d ",T->Data);
		PreOrder(T->Left);
		PreOrder(T->Right); 
	}
}
void InOrder(struct TreeNode*T){
	if(T!=NULL){
		InOrder(T->Left);
		printf("%d ",T->Data);
		InOrder(T->Right); 
	}
}
void PostOrder(struct TreeNode*T){
	if(T!=NULL){
		PostOrder(T->Left);
		PostOrder(T->Right); 
		printf("%d ",T->Data);
	}
}
int Count(struct TreeNode*T){
	if(T==NULL){
		return 0;
	}
	return 1+Count(T->Left)+Count(T->Right);
} 
struct TreeNode*FindMin(struct TreeNode*T){
	if(T==NULL){
		return NULL;
	}
	return (T->Left==NULL)?T:FindMin(T->Left);
}
struct TreeNode * Delete(struct TreeNode *T, int X) {
    struct TreeNode *q;

    if (T == NULL)
        return T;
    else if (X < T->Data)
        T->Left = Delete(T->Left, X);
    else if (X > T->Data)
        T->Right = Delete(T->Right, X);
    else  { /* X == T->Data */
        if (T->Left != NULL && T->Right != NULL) { /* 左右子树不空 */
            q = FindMin(T->Right);
            T->Data = q->Data;
            T->Right = Delete(T->Right, q->Data);
        } else { /* 左右子树至少有一个为空 */
            q = T;
            if (T->Left == NULL)
                T = T->Right;
            else if (T->Right == NULL)
                T = T->Left;
            free(q);
        }
    }

    return T;
}
 
int main(){
	int i,j;
	struct TreeNode*T;
	T=NULL;
	for(i=0;i<5;i++){
		scanf("%d",&j);
		T=Insert(T,j);
	}
	T=Delete(T,6);
	printf("\n");
	printf("先序:");PreOrder(T);
	printf("\n");
	printf("中序:");InOrder(T);
	printf("\n");
	printf("后序:");PostOrder(T); 
	printf("\n");
	int h=Height(T);
	printf("高度是:%d",h);
	int c=Count(T);
	printf("\n");
	printf("结点总数是:%d",c);

	return 0;
} 

你可能感兴趣的:(笔记)