栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

二叉树的遍历(层次,前序,中序,后序)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的遍历(层次,前序,中序,后序)

#include
using namespace std;
struct Bstnode {
	char data;
	Bstnode* left;
	Bstnode* right;
};
//创建新节点
Bstnode* GetNewNode(int data) {
	Bstnode* newNode = new Bstnode();
	(*newNode).data = data;
	newNode->left = newNode->right = NULL;
	return newNode;
}
//插入元素
Bstnode* Insert(Bstnode* root, int data) {
	if (root == NULL) {
		root = GetNewNode(data);
	}
	else if (data <= root->data) {
		root->left = Insert(root->left, data);
	}
	else {
		root->right = Insert(root->right, data);
	}
	return root;
}
//层次遍历
void LevelOrder(Bstnode* root) {
	if (root == NULL) return;
	queue Q;
	Q. push(root);
	while (!Q.empty()) {
		Bstnode* current = Q.front();
		cout << current->data << " ";
		if (current->left != NULL) Q.push(current->left);
		if (current->right != NULL) Q.push(current->right);
		Q.pop();
	}
}
//前序遍历
void Preorder(Bstnode* root) {
	if (root == NULL) return;
	cout << root->data <<" ";
	Preorder(root->left);
	Preorder(root->right);
}
//中序遍历
void Inorder(Bstnode* root) {
	if (root == NULL) return;
	Inorder(root->left);
	cout << root->data << " ";
	Inorder(root->right);
}
//后序遍历
void Postorder(Bstnode* root) {
	if (root == NULL) return;
	Postorder(root->left);
	Postorder(root->right);
	cout << root->data << " ";
}
int main() {
	Bstnode* root=NULL;
	root = Insert(root, 'F');root = Insert(root, 'D');root = Insert(root, 'J');
	root = Insert(root, 'B');root = Insert(root, 'E');root = Insert(root, 'G');
	root = Insert(root, 'K');root = Insert(root, 'A'); root = Insert(root, 'C');
	root = Insert(root, 'I');
	LevelOrder(root);
	cout << endl;
	Preorder(root);
	cout << endl;
	Inorder(root);
	cout << endl;
	Postorder(root);
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/630357.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号