构造二叉检索树

2021/11/15 23:12:25

本文主要是介绍构造二叉检索树,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

构造二叉检索树

本题目构造一棵二叉检索树。要求读入n个整数,以0结束。最后输出这棵树的先序序列。

输入格式:

输入n个整数,以0表示结束,数据间以空格隔开。

输出格式:

输出这棵树的先序序列,以一个空格隔开,结尾也有一个空格。

输入样例:

34 50 23 12 30 23 0
结尾无空行

输出样例:

34 23 12 23 30 50 
结尾无空行

AC代码:

#include<bits/stdc++.h>
using namespace std;
struct BSTree {
	int data;
	BSTree* left;
	BSTree* right;
};

void insert_Node(BSTree* &root,int n) {
	if(root==NULL) {
		root = new BSTree();
		root->data=n;
		root->left=NULL;
		root->right=NULL;
	} else {
		if(n<=root->data) {
			insert_Node(root->left,n);
		} else {
			insert_Node(root->right,n);
		}
	}
}

void preOder(BSTree* root) {
	if(root==NULL) {
		return;
	} else {
		cout<<root->data<<" ";
		preOder(root->left);
		preOder(root->right);
	}
}

int main() {
	BSTree* root=NULL;
	int n;
	cin>>n;
	while(n!=0) {
		insert_Node(root,n);
		cin>>n;
	}
	preOder(root);
	return 0;
}


这篇关于构造二叉检索树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程