1.使用引用
root能被&带出来
#include <iostream>
using namespace std;
struct BiNode//节点
{
int data;
BiNode *lchild, *rchild;
};
void Pre(BiNode* root)//前序遍历
{
if (root == NULL) return;
else
{
cout << root->data << endl;;
Pre(root->lchild);
Pre(root->rchild);
}
}
void In(BiNode* root)//中序遍历
{
if (root == NULL) return;
else
{
In(root->lchild);
cout << root->data << endl;;
In(root->rchild);
}
}
/*引用很重要*/
void Insert(BiNode* &root, BiNode* bt)//插入函数
{
if (root == NULL)
{
root = bt;
//cout << "root->data=" << root->data << endl;
return;
}
else
{
if (bt->data < root->data)//插入的节点小于根节点 插入左子树
{
Insert(root->lchild, bt);
}
else
{
Insert(root->rchild, bt);
}
}
}
void FindKey(BiNode* **&root**, int key)
{
if (root->data == key)
{
cout << "已找到" << endl;
cout << root->data;
return;
}
else
{
if (root->data >= key)
{
FindKey(root->lchild, key);
}
else
{
FindKey(root->rchild, key);
}
}
}
int main()
{
int i, n;
cin >> n;
BiNode *root;//建立根节点
**root = NULL;//root初始化**
int *s = new int[n];
for (i = 0; i < n; i++)//输入查找数组
{
cin >> s[i];
}
for (i = 0; i < n; i++)
{
**BiNode *bt = new BiNode;//每次都建立一个新的bt节点**
bt->data = s[i];//初始化bt
bt->lchild = NULL;
bt->rchild = NULL;
Insert(root, bt);//将bt插入二叉排序树
}
cout << "前序遍历:" << endl;
Pre(root);
cout << "中序遍历:" << endl;
In(root);
int k;
cin >> k;
FindKey(root, k);//查找
return 0;
}
2.用return带出来
#include <iostream>
using namespace std;
struct BiNode
{
int data;
struct BiNode *lchild, *rchild;
};
void Pre(BiNode* root)
{
if (root == NULL)//if要注意
{
return;
}
else
{
cout << root->data;
Pre(root->lchild);
Pre(root->rchild);
}
}
BiNode* Insert(BiNode* root, BiNode* bt)//插入函数
{
if (root == NULL)
{
root = bt;
}
else
{
if (bt->data < root->data)
{
root->lchild = Insert(root->lchild, bt);
}
else
{
root->rchild = Insert(root->rchild, bt);
}
return root;
}
}
//未考虑查找失败的情况
BiNode* Findkey(BiNode* root, int key)//查找
{
if (key == root->data)//只有在找到的时候才会返回 函数才会结束
{
cout << root->data;
return root;
}
else
{
if (root->data >= key)
{
Findkey(root->lchild, key);
}
else
{
Findkey(root->rchild, key);
}
}
}
int main()
{
int i, n;
cin >> n;
BiNode *root;
root = NULL;
int *s = new int[n];
for (i = 0; i < n; i++)
{
cin >> s[i];
}
for (i = 0; i < n; i++)
{
BiNode *bt = new BiNode;
bt->data = s[i];
bt->lchild = NULL;
bt->rchild = NULL;
root = Insert(root, bt);
}
int k;
cin >> k;
Findkey(root, k);
return 0;
}
- &很重要
- root注意初始化
- bt每次都要重新创建 给它分配新的地址空间
- 注意return的返回条件
- 注意判断的if > <的判断(判断失误可能会让指针一直是nullpr)
- 下次把删除实现
- 平衡二叉树暂时可能不会考