#include<iostream>
using namespace std;
const int N = 1000010;
int a[] = { 0,3,1,5,2,4 };
struct treenode {
int key;
int ls, rs;
};
treenode tree[N];
int id = 1, root = 1;
void buildBST()
{
tree[id].key = a[1]; tree[id].ls = tree[1].rs = 0;
for (int i = 2; i <= 5; i++)
{
tree[++id].key = a[i], tree[id].ls = tree[id].rs = 0;
root = 1;
while (root)
{
if (tree[id].key < tree[root].key)
{
if (tree[root].ls == 0)
{
tree[root].ls = id;
break;
}
else root = tree[root].ls;
}
else
{
if (tree[root].rs == 0)
{
tree[root].rs = id;
break;
}
else root = tree[root].rs;
}
}
}
}
void preorder(int u)
{
if (u == 0) return;
cout << tree[u].key << " ";
preorder(tree[u].ls);
preorder(tree[u].rs);
}
void inorder(int u)
{
if (u == 0) return;
inorder(tree[u].ls);
cout << tree[u].key << " ";
inorder(tree[u].rs);
}
void postorder(int u)
{
if (u == 0) return;
postorder(tree[u].ls);
postorder(tree[u].rs);
cout << tree[u].key << " ";
}
int main() {
buildBST();
preorder(1);
cout << endl;
inorder(1);
cout << endl;
postorder(1);
return 0;
}
二叉搜索树以及前序中序后序遍历
最新推荐文章于 2024-08-30 16:00:44 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)