先给定想要构建的树的数据:
//给定数组为:
int data[8]={5, 2, 1, 3, 4, 7, 6, 8};
所给数据的构建的树,及先序序列如下,
完整代码:
#include<stdio.h>
int data[8]={5, 2, 1, 3, 4, 7, 6, 8};
struct node{
int data;
node* lchild;
node* rchild;
};
node* newNode(int x){
node* Node = new node;
Node->data = x;
Node->lchild = Node->rchild = NULL;
return Node;
}
void insert(node* &root, int x){
if(root == NULL){
// printf("已插入data:%d!\n",x);
root = newNode(x);
return;
}
if(root->data > x){
// printf("往左子树插入\n");
insert(root->lchild, x);
}else{
// printf("往右子树插入\n");
insert(root->rchild, x);
}
}
node* Create(int data[], int n){
node* root = NULL;
printf("insert begin!\n");
for(int i=0;i<n;i++){
insert(root, data[i]);
printf("插入 %d 完毕\n", data[i]);
}
printf("insert success!\n");
return root;
}
void preOrder(node* root){
if(root == NULL){
return;
}
printf("%d ", root->data);
preOrder(root->lchild);
preOrder(root->rchild);
}
int main(){
node* root = Create(data,8);
printf("先序遍历开始\n");
preOrder(root);
return 0;
}