二叉树的三种非递归遍历

本文介绍了如何在C++中使用结构体TreeNode构建二叉树,并提供了三个遍历方法:前序遍历(front),中序遍历(mid),和后序遍历(back)的实现,通过递归的方式展示了如何使用这些函数对输入字符串进行操作。
摘要由CSDN通过智能技术生成


#include <iostream>
#include<stack>
#include<vector>
#include<string>
#include<stack>
using namespace std;

struct TreeNode
{
	char data;
	struct TreeNode* left;
	struct TreeNode* right;
	TreeNode(char x) :data(x), left(nullptr), right(nullptr){}
};
struct TreeNode* BuildTree(const string & datas,int& i)
{

	if (i == datas.size() || datas[i] == '#')
	{
		i++;
		return nullptr;
	}
	TreeNode* root = new TreeNode(datas[(i++)]);
	root->left = BuildTree(datas,i);
	root->right = BuildTree(datas,i);
	return root;
}
string front(TreeNode* point)
{
	string result;
	struct TreeNode* root = point;
	if (!root)
	{
		return result;
	}
	stack<TreeNode*>st;
	st.push(root);
	while ( !(st.empty()))
	{
		TreeNode* node = st.top();
		st.pop();
		result += node -> data;
		result += ' ';
		if (node->right) st.push(node->right);
		if (node->left) st.push(node->left);
}
	return result;
}
string mid(struct TreeNode* point)
{
	string result;
	stack<TreeNode*>st;
	struct TreeNode* root = point;
	while (root != nullptr ||! (st.empty()))
	{
		while (root != nullptr)
		{
			st.push(root);
			root = root->left;
		}
		root = st.top();
		st.pop();
		result += root->data;
		result += ' ';
		root = root->right;
	}
	return result;
}
string back(struct TreeNode* root)
{

	
	if (root == nullptr)
	{
		return "";
	}
	stack<TreeNode*>s1;
	stack<TreeNode*> s2;
	string result;

	s1.push(root);
	while (!s1.empty()) {
		TreeNode* node = s1.top();
		s1.pop();
		s2.push(node);

		if (node->left) {
			s1.push(node->left);
		}
		if (node->right) {
			s1.push(node->right);
		}
	}

	while (!s2.empty()) {
		TreeNode* node = s2.top();
		s2.pop();
		result += node->data;
		result += ' ';
	}

	return result;
}
int main()
{
	string good;
	cin >> good;
	int i = 0;
	cout<<front(BuildTree(good,i));
	cout << '\n';
	i = 0;
	cout << mid(BuildTree(good, i));
	cout << '\n';
	i = 0;
	cout << back(BuildTree(good, i));
	cout << '\n';
	i = 0;
	cout << front(BuildTree(good, i));
	cout << '\n';
	i = 0;
	cout << mid(BuildTree(good, i));
	cout << '\n';
	i = 0;
	cout << back(BuildTree(good, i));
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值