🤨Step1 头文件的引入

image.png
😄 Step2 定义树节点结构

image.png
😏 Step3 声明树节点 和 声明树节点指针

image.png
😊 Step4 创建二叉树函数

image.png
😳 Step5 搜索二叉树中节点

image.png
🙄 Step6 主程序的编写

image.png
😜 Step7 调用搜索

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;
// 本程序目的: 搜索节点
// 函数1 创建二叉树
btree create_tree(btree root, int val){
// 定义变量
btree newnode, current, backup = NULL;
// 新的节点的创建
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;
}
// 函数2 搜索节点
btree search(btree ptr, int val){
int i = 1;
// 一直循环
while (1)
{
if (ptr == NULL){
return NULL;
}
// 统计一共找了几次
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;// 用来存储需要查找的值
btree ptr = NULL;
cout << "原始数组内容:" << endl;
for (i = 0; i < 11; i++){
ptr = create_tree(ptr, arr[i]);
cout << "[" << arr[i] << "]";
}
cout << endl;
cout << "请输入需要查找的值:" << endl;
cin >> data;
// 开始进行查找
if ((search(ptr, data) != NULL))
cout << "你要查找的值[:" << data << "] 有找到" << endl;
else
cout << "您要找的值,没有找到!" << endl;
system("pause");
return 0;
}
网友评论