欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

算法与数据结构考研试题精析-第9章算法设计题29

程序员文章站 2022-05-20 10:25:55
...

写一个递归算法确定二叉排序树中各结点的平衡因子,同时返回二叉树中非叶子结点个数。

//题目:计算二叉排序树中各结点的平衡因子,同时返回非叶子结点个数
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int Status;

typedef struct Node
{
    int data;
    int bf;
    struct Node *llink,*rlink;
}Node,*Tree;

Status SearchBST(Tree T,int key,Tree f,Tree *p);
Status InsertBST(Tree *T,int e);
void Factor_Make(Tree T,int *h,int *unleaf);

int main()
{
    Tree T;
	T=(Tree)malloc(sizeof(Node));
	T=NULL;
    int e;
    printf("What number you want to search--0 to quit:");
    scanf("%d",&e);
    while(e)
    {
        if(!InsertBST(&T,e))
            printf("Done!");
        else
            printf("It`s been inserted for the first time.");
        printf("\nWhat number you want to search--0 to quit:");
        scanf("%d",&e);
    }
	int h,unleaf;
	h=unleaf=0;
	Factor_Make(T,&h,&unleaf);
	printf("树的高度为:%d.树的非叶子结点个数为:%d\n",h,unleaf);
    return 0;
}
Status SearchBST(Tree T,int key,Tree f,Tree *p)
{
    if(!T)
    {
        *p=f;
        return FALSE;
    }
    else if(key==T->data)
    {
        *p=T;
        return TRUE;
    }
    else if(key<T->data)
    {
        return SearchBST(T->llink,key,T,p);
    }
    else
        return SearchBST(T->rlink,key,T,p);
}

Status InsertBST(Tree *T,int e)
{
    Tree p;
    p=(Tree)malloc(sizeof(Node));

    if(!SearchBST(*T,e,NULL,&p))
    {
        Tree s;
        s=(Tree)malloc(sizeof(Node));
        s->data=e;
        s->llink=s->rlink=NULL;
        s->bf=0;
        if(!p)
            (*T)=s;
        else if(e<p->data)
            p->llink=s;
        else
            p->rlink=s;
        return TRUE;
    }
    else
        return FALSE;
}
void Factor_Make(Tree T,int *h,int *unleaf)
{
    if(T)
    {
        int left,right;
		left=right=0;
		Factor_Make(T->llink,&left,unleaf);
        Factor_Make(T->rlink,&right,unleaf);
		T->bf=left-right;
        (*h)=1+(left>right?left:right);
        if(T->llink || T->rlink)
            (*unleaf)++;
    }
}