65,210
社区成员
发帖
与我相关
我的任务
分享
//现有一棵二叉树和一个有序数组,要求通过这棵二叉树构造有序数组。
//它们的类型声明如下,请定义有序数组的构造函数。
class SEQUENCE;
class TREE{
int item;
TREE *left, *right;
friend SEQUENCE;
public:
//请在此定义函数
};
class SEQUENCE{
int *items;
int size;
public:
SEQUENCE(TREE &);
};
//释放内存的自己写
#include <stdio.h>
#include <malloc.h>
typedef struct tag_node
{
int data;
struct tag_node* left, *right;
} *tree, node;
void insert(tree t, int value)
{
tree p = t, curr = t->left, new_node = NULL;
while (curr)
{
if (value == curr->data) return;
p = curr;
if (value < curr->data) curr = curr->left;
else curr = curr->right;
}
new_node = (tree)malloc(sizeof(node));
new_node->data = value;
new_node->left = new_node->right = NULL;
if (p == t || value < p->data) p->left = new_node;
else p->right = new_node;
}
void print(tree t)
{
if (!t) return;
print(t->left);
printf("%d ", t->data);
print(t->right);
}
int main()
{
int data[] = {6,8,7,4,5,2,9,54,3};
int i;
tree t = (tree)malloc(sizeof(node));
t->left = t->right = NULL;
for (i = 0; i < sizeof(data)/sizeof(int); ++i)
insert(t, data[i]);
print(t->left);
return 0;
}