您的位置:首页 > 编程语言 > C语言/C++

关于C++二分搜索树的中序遍历和先序遍历

2015-12-19 22:15 330 查看
这里即将介绍如何对一个二分查找树进行中序遍历和先序遍历进行操作

下面是源代码其中包括自己写的一段建树操作的函数

#include<iostream>
using namespace std;
struct Node
{
Node *lc;
Node *rc;
int data;
Node(int a)
{
data = a;
lc = NULL;
rc = NULL;
}
};
void built(Node* &root , int a)
{
if(root == NULL)
{
root = new Node(a);
root->lc = NULL;
root->rc = NULL;
}
else
{
if(a > root->data)
{
return built(root->rc , a);
}
else
{
return built(root->lc , a);
}
}
}
void inorder(Node* root)
{
if(root != NULL)//即为先对左子树进行遍历,到底后输入在逐步对右子树进行遍历,也可以验证二分搜索树是否有序
{
inorder(root->lc);
cout << root->data << " ";
inorder(root->rc);
}
}
void preorder(Node* root)
{
if(root != NULL)//先输出根值在对左子树进行遍历,最后对右子树进行遍历
{
cout << root->data << " ";
preorder(root->lc);
preorder(root->rc);
}
}
int main()
{
int n;
cout << "请输入元素数目:";
while(cin >> n && n != 0)
{
Node *root = NULL;
cout << "请输入元素:";
for(int i = 0 ; i < n ; i ++)
{
int a;
cin >> a;
built(root,a);
}
cout << "中序遍历结果为:";
inorder(root);
cout << endl;
cout << "前序遍历结果为:";
preorder(root);
cout << endl << "请输入下一次元素数目,结束请输入'0':";
}
cout << endl;
return 0;
}


运行结果如图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: