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

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

二叉树的遍历层次,前序,中序,后序)
#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);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5636237.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存