求出在一棵二叉排序树上查找关键字K所走过的路径。
代码如下
#include <bits/stdc++.h>
using namespace std;
struct node
{
int x;
int lch, rch;
};
node tree[10000];
void init(int n)
{
for (int i = 1; i <= n; i++)
{
tree[i].rch = 0, tree[i].lch = 0, tree[i].x = 0;
}
}
void add(int x, int id, int i) //把数加入二叉排序树中
{
if (tree[id].x > x)
{
if (tree[id].lch == 0)
{
tree[id].lch = i;
return;
}
else
{
add(x, tree[id].lch, i);
}
}
else if (tree[id].x == x)
return;
else
{
if (tree[id].rch == 0)
{
tree[id].rch = i;
return;
}
else
{
add(x, tree[id].rch, i);
}
}
}
int f = 0;
void find(int k, int id)
{
if (f)
cout << "->";
f = 1;
cout << tree[id].x;
if (tree[id].x == k) //找到了
return;
if (k < tree[id].x) //左子树找
{
if (tree[id].lch == 0)
cout << "没找到key";
else
find(k, tree[id].lch);
}
else if (k > tree[id].x) //右子树找
{
if (tree[id].rch == 0)
cout << "没找到key";
else
find(k, tree[id].rch);
}
}
int main()
{
cout << "输入元素个数: ";
int n;
cin >> n;
cout << "输入个元素值: " << endl;
for (int i = 1; i <= n; i++)
{
cin >> tree[i].x;
add(tree[i].x, 0, i);
}
cout << "输入key值: " << endl;
int key;
cin >> key;
find(key, 1);
}
运行结果