二叉搜索树的层次遍历和先序、中序、后序遍历

 这是一颗二叉搜索树,可以按层次遍历和按先序、中序、后序遍历。

 

 源码

#include<iostream>
using namespace std;
#include<queue>

struct Node
{
	int data;
	Node* left;
	Node* right;                                 
};

Node* getnewNode(int n)
{
	Node* temp;
	temp = new Node;
	temp->data = n;
	temp->left = NULL;
	temp->right = NULL;
	return temp;
}

void Insert(Node*& root, int n)
{
	if (root == NULL)
		root = getnewNode(n);
	else if (n <= root->data)
		Insert(root->left, n);
	else if (n > root->data)
		Insert(root->right, n);
}
//层级遍历
void Levelorder(Node* root)
{
	if (root == NULL)
		return;
	queue<Node*>Q;
	Q.push(root);
	while (!Q.empty())
	{
		Node* current;
		current = Q.front();
		cout << current->data << " ";
		Q.pop();
		if (current->left != NULL) Q.push(current->left);
		if (current->right != NULL) Q.push(current->right);
	}
}
//前序遍历
void Preorder(Node* root)
{
	if (root == NULL) return;
	cout << root->data << " ";
	Preorder(root->left);
	Preorder(root->right);
}
//中序遍历
void Inorder(Node* root)
{
	if (root == NULL) return;
	Inorder(root->left);
	cout << root->data << " ";
	Inorder(root->right);
}
//后序遍历
void Postorder(Node* root)
{
	if (root == NULL) return;
	Postorder(root->left);
	Postorder(root->right);
	cout << root->data << " ";
}
int main()
{
	Node* root = NULL;
	Insert(root, 5);
	Insert(root, 4);
	Insert(root, 7);
	Insert(root, 6);
	Insert(root, 8);
	Insert(root, 1);
	Insert(root, 2);
	cout << "层次遍历:";
	Levelorder(root);
	cout << endl << "前序遍历:";
	Preorder(root);
	cout << endl << "中序遍历:";
	Inorder(root);
	cout << endl << "后序遍历:";
	Postorder(root);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值