您的位置:首页 > 其它

SDUT 2128 树结构练习——排序二叉树的中序遍历

2016-07-23 11:08 330 查看
点击打开题目链接

#include <bits/stdc++.h>
using namespace std;

struct node
{
int data;
node *left, *right;
};

int k;
int _array[1010];
void Inorder(node *root);
void Insert(node *(&root), int x);
node *creat(int lenth, int _array[]);

int main()
{
node *root;
int n;
while(cin >> n)
{
k = 0;
for(int i = 0; i < n; i++)
{
cin >> _array[i];
}
root = creat(n, _array);
Inorder(root);
for(int i = 0; i < k; i++)
{
if(i == k-1)
{
cout << _array[i] << endl;
}
else
{
cout << _array[i] << ' ';
}
}
}
return 0;
}

node *creat(int lenth, int _string[])
{
node *root = NULL;
int i = 0;
while(i < lenth)
{
Insert(root, _string[i]);
i++;
}
return root;
}

void Insert(node *(&root), int x)
{
if(!root)
{
root = new node;
root -> data = x;
root -> left = NULL;
root -> right = NULL;
}
else if(x < root -> data)
{
Insert(root -> left, x);
}
else
{
Insert(root -> right, x);
}
}

void Inorder(node *root)
{
if(root)
{
Inorder(root -> left);
_array[k++] = root -> data;
Inorder(root -> right);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BST