c/c++ 给定数组后按大小顺序构建树,并输出先序序列(完整可运行代码)

先给定想要构建的树的数据:

//给定数组为:
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;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值