??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;
}