0
点赞
收藏
分享

微信扫一扫

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

勇敢乌龟 2022-04-13 阅读 11
c++

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

//给定数组为:
int data[8]={5, 2, 1, 3, 4, 7, 6, 8};

所给数据的构建的树,及先序序列如下,
在这里插入图片描述
完整代码:

#include<stdio.h>
#include<queue>
using namespace std;
int data[8]={5,2,1,3,4,7,6,8};
struct node{
	int data;
	node* lchild;
	node* rchild;
} Node;

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 条评论