例题10.4二叉排序树(华科)

二叉排序树

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

例题10.4二叉排序树(华科)

关键:二叉排序树的插入、前序、中序、后序遍历

#include<vector>
using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

TreeNode* insert(TreeNode* root, int x) {
	if (root == NULL) {
		root = new TreeNode(x);
	}
	else if (x < root->val) {
		root->left = insert(root->left, x);
	}
	else if (x > root->val) {
		root->right = insert(root->right, x);
	}
	return root;
}

void preOrder(TreeNode* root) {
	if (root == nullptr)
		return;
	cout << root->val<<" ";
	if (root->left != nullptr) {
		preOrder(root->left);
	}
	if (root->right != nullptr) {
		preOrder(root->right);
	}
}

void InOrder(TreeNode* root) {
	if (root == nullptr)
		return;
	if (root->left != nullptr) {
		InOrder(root->left);
	}
	cout << root->val << " ";
	if (root->right != nullptr) {
		InOrder(root->right);
	}
}

void postOrder(TreeNode* root) {
	if (root == nullptr)
		return;
	if (root->left != nullptr) {
		postOrder(root->left);
	}
	if (root->right != nullptr) {
		postOrder(root->right);
	}
	cout << root->val << " ";
}

int main() {
	int n;
	while (cin >> n) {
		TreeNode* root = NULL;
		for (int i = 0; i < n; i++) {
			int x;
			cin >> x;
			root = insert(root, x);
		}
		preOrder(root);
		cout << endl;
		InOrder(root);
		cout << endl;
		postOrder(root);
		cout << endl;
	}
	return 0;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
08-08 18:20
职场水母:这题思路是什么,我目前想的一个暴力方法就是先把这个链表遍历一遍,用哈希表存储出现次数,然后再根据哈希表来一个一个删除节点,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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