#include <iostream>
using namespace std;
typedef struct Node{
int data;
struct Node*lchild;
struct Node*rchild;
struct Node*par;
}*BST;
//递归建立二叉排序树
int Res_Creat(BST &root, int key)
{
if(root == NULL)
{
root = new Node;
root->data = key;
root->lchild = NULL;
root->rchild = NULL;
root->par = NULL;
return 1;
}
else if(root->data == key)
return 0;
else if(root->data > key)
return Res_Creat(root->lchild, key);
else
return Res_Creat(root->rchild, key);
}
//非递归建立二叉排序树
int Non_Res_Creat(BST &root, int key)
{
Node *par_node = NULL;
Node *t = root;
while(t)
{
par_node = t;
if(key < t->data)
t = t->lchild;
else if(key > t->data)
t = t->rchild;
else
return 0;
}
Node *temp = new Node;
temp->data = key;
temp->lchild = NULL;
temp->rchild = NULL;
temp->par = par_node;
if(par_node == NULL)
root = temp;
else
{
if(key < par_node->data)
par_node->lchild = temp;
else
par_node->rchild = temp;
}
}
//中序遍历输出
void Inordertraversal(BST root)
{
if(root)
{
Inordertraversal(root->lchild);
cout << root->data << " ";
Inordertraversal(root->rchild);
}
}
int main()
{
BST root = NULL;
int arr[] = { 17,12,19,10,15,18,25,8,11,13,16,22};
for(int i = 0; i < 12; i++)
Res_Creat(root, arr[i]);
Inordertraversal(root);
cout << endl;
for(int i = 0; i < 12; i++)
Non_Res_Creat(root, arr[i]);
Inordertraversal(root);
return 0;
}
二叉排序树的递归与非递归建立 C++实现
最新推荐文章于 2022-07-26 10:20:04 发布