题解 | #二叉排序树#

二叉排序树

https://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3

学会利用递归思想来建立排序树
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<queue>
using namespace std;

struct TreeNode {
	int data;
	TreeNode* leftchild;
	TreeNode* rightchild;
};

TreeNode* BuildTree(TreeNode* & root, int n) {  //建立排序树
	if (root == NULL)
	{
		root = new TreeNode;
		root->data = n;
		root->leftchild = NULL;
		root->rightchild = NULL;
	}
	else if (n < root->data) {
		root->leftchild = BuildTree(root->leftchild, n);
	}
	else if (n > root->data) {
		root->rightchild = BuildTree(root->rightchild, n);
	}
	return root;
}

void Preorder(TreeNode* t) {
	if (t == NULL) return;
	else {
		cout << t->data << ' ';
		Preorder(t->leftchild);
		Preorder(t->rightchild);
	}
}

void Inorder(TreeNode* t) {
	if (t == NULL) return;
	else {
		Inorder(t->leftchild);
		cout << t->data << ' ';
		Inorder(t->rightchild);
	}
}

void Postorder(TreeNode* t) {
	if (t == NULL) return;
	else {
		Postorder(t->leftchild);
		Postorder(t->rightchild);
		cout << t->data << ' ';
	}
}

int main() {
	int n;
	int num[100];
	while (cin >> n) {
		TreeNode* root = NULL;
		for (int i = 0; i < n; i++) {
			cin >> num[i];
			BuildTree(root, num[i]);
		}
		Preorder(root);
		cout << endl;
		Inorder(root);
		cout << endl;
		Postorder(root);
		cout << endl;
	
	}


}

全部评论

相关推荐

06-26 22:20
门头沟学院 Java
码农索隆:让你把简历发给她,她说一些套话,然后让你加一个人,说这个人给你改简历,然后开始卖课
我的求职精神状态
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务