14周-項目2 - 二叉樹排序樹中查找的路徑

問題及代碼:

設計一個算法,輸出在二叉排序中查找時查找某個關鍵字經過的路徑。

#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef int KeyType;                    //定義關鍵字類型
typedef char InfoType;
typedef struct node                     //記錄類型
{
    KeyType key;                        //關鍵字項
    InfoType data;                      //其他數據域
    struct node *lchild,*rchild;        //左右孩子指針
} BSTNode;
int path[MaxSize];                      //全局變量,用於存放路徑
void DispBST(BSTNode *b);               //函數說明
int InsertBST(BSTNode *&p,KeyType k)    //在以*p爲根節點的BST中插入一個關鍵字爲k的節點
{
    if (p==NULL)                        //原樹爲空, 新插入的記錄爲根節點
    {
        p=(BSTNode *)malloc(sizeof(BSTNode));
        p->key=k;
        p->lchild=p->rchild=NULL;
        return 1;
    }
    else if (k==p->key)
        return 0;
    else if (k<p->key)
        return InsertBST(p->lchild,k);  //插入到*p的左子樹中
    else
        return InsertBST(p->rchild,k);  //插入到*p的右子樹中
}
BSTNode *CreatBST(KeyType A[],int n)
//由數組A中的關鍵字建立一棵二叉排序樹
{
    BSTNode *bt=NULL;                   //初始時bt爲空樹
    int i=0;
    while (i<n)
        InsertBST(bt,A[i++]);       //將A[i]插入二叉排序樹T中
    return bt;                          //返回建立的二叉排序樹的根指針
}

//在二叉排序樹中查找,記經過的節點記錄在path中,返回值爲最後查找節點在path中存儲的下標
int SearchBST(BSTNode *bt,KeyType k,KeyType path[],int i)
{
    if (bt==NULL)
        return i;
    else if (k==bt->key)    //找到了節點
    {
        path[i+1]=bt->key;  //輸出其路徑
        return i+1;
    }
    else
    {
        path[i+1]=bt->key;
        if (k<bt->key)
            SearchBST(bt->lchild,k,path,i+1);  //在左子樹中遞歸查找
        else
            SearchBST(bt->rchild,k,path,i+1);  //在右子樹中遞歸查找
    }
}

//查找並顯示經過的路徑
void SearchResult(BSTNode *bt, int k1)
{
    int r, j;
    r = SearchBST(bt,k1,path,-1);
    for (j=0; j<=r; j++)
        printf("%3d",path[j]);
    printf("\n");
}

void DispBST(BSTNode *bt)
//以括號表示法輸出二叉排序樹bt
{
    if (bt!=NULL)
    {
        printf("%d",bt->key);
        if (bt->lchild!=NULL || bt->rchild!=NULL)
        {
            printf("(");
            DispBST(bt->lchild);
            if (bt->rchild!=NULL) printf(",");
            DispBST(bt->rchild);
            printf(")");
        }
    }
}

int main()
{
    BSTNode *bt;
    KeyType k1=65, k2=32;
    int a[]= {43,91,10,18,82,65,33,59,27,73},n=10;
    printf("創建的BST樹:");
    bt=CreatBST(a,n);
    DispBST(bt);
    printf("\n");
    printf("  查找%d關鍵字:",k1);
    SearchResult(bt,k1);
    printf("  查找%d關鍵字:",k2);
    SearchResult(bt,k2);
    return 0;
}


輸出及結果:



分析:

主思想是折半思想

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章