描述
已知二叉树T的结点形式为(llink,data,count,rlink),在树中查找值为x的结点,若找到,则计数(count)加1;否则,作为一个新结点插入树中,插入后仍为二叉排序树。请写出其非递归算法。
输入
多组数据,每组数据3行。第一行为二叉排序树的结点数n,第二行为空格分隔的n个数字,对应二叉排序树中的n个结点,第三行为查找的值x。n=0时输入结束。
输出
每组数据输出两行。第一行为二叉排序树的中序序列(空格分隔),第二行为其对应的计数count。
输入样例 1
5
1 2 3 4 5
3
6
1 3 4 5 6 7
2
0
输出样例 1
1 2 3 4 5 0 0 1 0 0 1 2 3 4 5 6 7 0 0 0 0 0 0 0
思路:
注:用的是lchild和rchild,比较习惯这个写法。
首先在寻找和插入之前需要先建立,关于建立二叉排序树和遍历就不多说了,如果还不太会的话可以看我的这篇文章:
4016-二叉排序树的判定(C++,附思路)_鹤天寻的博客-CSDN博客https://blog.csdn.net/qq_54416938/article/details/121612791?spm=1001.2014.3001.5501注意题目里说不要递归(但是你递归oj也看不出来hhh,只要输出正确)
设置全局数组arr,在创建的时候标记该data对应下标的value为1,这样先存起来,方便之后的查找,类似于哈希散列。
ass是辅助树,便于确定我们所建立的二叉树的根节点。因为在遍历的时候,bt指向的已经不是自己的根节点了,但是之后打印输出又需要传送bt的根节点,所以先放到一个ass里存起来。
建立好树之后遍历BTree bt,对刚才输入的数字进行判断,若arr的值是0,说明是新节点,那么就要寻找到合适的位置插入;否则是老节点,继续遍历左右子节点寻找值相等的节点,找到的话设置count=1后直接return即可;
若是新节点,那么首先比较它和当前节点的数值大小,若是比当前节点的数值大,那么bt不断遍历更新,直到该值比当前节点大,且比当前节点的右子节点小的节点,这个节点就是目标节点,用该值建立新结点,建立bt和新结点之间的联系即可,反之同理;
输出的时候可以用结点的总个数来控制输出空格的个数,那么就要注意要提前更新,复制n的值到两个变量里存储,并且参数写引用!!
最后别忘了把辅助数组arr的值全部置零。
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<stack>
#include<set>
#include<map>
using namespace std;
typedef struct BNode
{
int data, count;
struct BNode* lchild, * rchild;
}*BTree, BNode;
int arr[100];
void Create(BTree& bt, int x)
{
if (!bt)
{
bt = new BNode;
bt->data = x;
arr[x] = 1;
bt->count = 0;
bt->lchild = NULL;
bt->rchild = NULL;
}
else
{
if (x < bt->data)
Create(bt->lchild, x);
else
Create(bt->rchild, x);
}
}
void Traverse(BTree &bt,int x)
{
while (bt)
{
if (arr[x] == 0)
{
if (bt->data < x)
{
while (bt->rchild != NULL && bt->rchild->data < x)
bt = bt->rchild;
}
else if (bt->data < x)
{
while (bt->lchild != NULL && bt->lchild->data > x)
bt = bt->lchild;
}
BTree temp = new BNode;
temp->data = x;
temp->count = 0;
temp->rchild = NULL;
temp->lchild = NULL;
bt->lchild = temp;
arr[x] = 1;
}
else
{
if (bt->data < x)
bt = bt->rchild;
else if (bt->data > x)
bt = bt->lchild;
else
{
bt->count=1;
return;
}
}
}
}
void PrintData(BTree bt,int& n)
{
if(bt)
{
cout << bt->data;
n--;
if (n)
cout << ' ';
PrintData(bt->lchild,n);
PrintData(bt->rchild,n);
}
}
void PrintCount(BTree bt,int& n)
{
if (bt)
{
cout << bt->count;
n--;
if (n)
cout << ' ';
PrintCount(bt->lchild,n);
PrintCount(bt->rchild,n);
}
}
int main()
{
int n;
while (cin >> n && n != 0)
{
BTree bt=NULL,ass;
int x;
for (int i = 0; i < n; i++)
{
cin >> x;
Create(bt, x);
}
cin >> x;
if (arr[x] == 0)
n += 1;
ass = bt;
Traverse(bt, x);
int n1 = n, n2 = n;
PrintData(ass,n1);
cout << endl;
PrintCount(ass,n2);
cout << endl;
for (int i = 0; i < 100; i++)
arr[i] = 0;
}
return 0;
}