?????二叉樹查找過(guò)程

??Step1 頭文件的引入

image.png

?? Step2 定義樹節(jié)點(diǎn)結(jié)構(gòu)

image.png

?? Step3 聲明樹節(jié)點(diǎn) 和 聲明樹節(jié)點(diǎn)指針

image.png

?? Step4 創(chuàng)建二叉樹函數(shù)

image.png

?? Step5 搜索二叉樹中節(jié)點(diǎn)

image.png

?? Step6 主程序的編寫

image.png

?? Step7 調(diào)用搜索

image.png
附上代碼
#include <iostream>
#include <stdlib.h>
using namespace std;

struct tree
{
    int data;
    struct tree *left, *right;
};

typedef struct tree node;
typedef node *btree;

// 本程序目的: 搜索節(jié)點(diǎn)
// 函數(shù)1 創(chuàng)建二叉樹
btree create_tree(btree root, int val){
    // 定義變量
    btree newnode, current, backup = NULL;
    // 新的節(jié)點(diǎn)的創(chuàng)建
    newnode = (btree)malloc(sizeof(node));
    newnode->data = val;
    newnode->left = NULL;
    newnode->right = NULL;
    // 開始
    if (root == NULL)
    {
        root = newnode;
        return root;
    }
    else
    {
        for (current = root; current != NULL;)
        {
            backup = current;
            if (current->data > val)
                current = current->left;
            else
                current = current->right;
        }
        if (backup->data >val)
            backup->left = newnode;
        else
            backup->right = newnode;
    }
    return root;
}
// 函數(shù)2 搜索節(jié)點(diǎn)
btree search(btree ptr, int val){
    int i = 1;
    // 一直循環(huán)
    while (1)
    {
        if (ptr == NULL){
            return NULL;
        }
        // 統(tǒng)計(jì)一共找了幾次
        if (ptr->data == val){
            cout << "共查找" << i << "次" << endl;
            // 找到之后就返回
            return ptr;
        }
        else if(ptr->data >val){
            ptr = ptr->left;
        }
        else{
            ptr = ptr->right;
        }
        i++;
    }
}
int main(){
    // 原始的查找
    // 在找到第一次之后,就退出了
    int arr[] = { 7, 1, 4, 2, 8, 13, 12, 11, 15, 9, 5,11 };
    int i = 0;
    int data;// 用來(lái)存儲(chǔ)需要查找的值
    btree ptr = NULL;
    cout << "原始數(shù)組內(nèi)容:" << endl;
    for (i = 0; i < 11; i++){
        ptr = create_tree(ptr, arr[i]);
        cout << "[" << arr[i] << "]";
    }
    cout << endl;

    cout << "請(qǐng)輸入需要查找的值:" << endl;
    cin >> data;

    // 開始進(jìn)行查找
    if ((search(ptr, data) != NULL))
        cout << "你要查找的值[:" << data << "] 有找到" << endl;
    else
        cout << "您要找的值,沒有找到!" << endl;

    system("pause");
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容