左神算法学习日记——二叉树(一)

本文详细介绍了二叉树的前序、中序和后序非递归遍历算法实现,通过使用栈来替代递归调用,提供了一种更节省内存的遍历方式。代码示例清晰展示了如何利用栈进行节点访问,适用于理解和实践二叉树的遍历过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 二叉树遍历,非递归版

#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include<xfunctional>
#include<sstream>
using namespace std;


class node
{
public:
	char num;
	node* left;
	node* right;
	node()
	{
		num = 0;
		left = NULL;
		right = NULL;
	}
	node(char n)
	{
		num = n;
		left = NULL;
		right = NULL;
	}
};

void pre(node* head)
{
	if (head != NULL)
	{
		stack<node*> sta;
		sta.push(head);
		while (!sta.empty())
		{
			head = sta.top();
			cout << head->num << "  ";
			sta.pop();
			if (head->right)
				sta.push(head->right);
			if (head->left)
				sta.push(head->left);
		}
	}
	cout << endl;
}

void mid(node* head)
{
	if (head != NULL)
	{
		stack<node*> sta;
		while (!sta.empty()||head)
		{
			if (head)
			{
				sta.push(head);
				head = head->left;
			}
			else
			{
				head = sta.top();
				sta.pop();
				cout << head->num << "  ";
				head = head->right;
			}
		}
	}
	cout << endl;
}

void beh(node* head)
{
	if (head != NULL)
	{
		stack<node*> sta;
		stack<char> help;
		sta.push(head);
		while (!sta.empty())
		{
			head = sta.top();
			help.push(sta.top()->num);
			sta.pop();
			if (head->left)
				sta.push(head->left);
			if (head->right)
				sta.push(head->right);
		}
		while (!help.empty())
		{
			cout << help.top()<<"  ";
			help.pop();
		}
	}
	cout << endl;
}

void creatT(node* head)
{
	static char n = 'B';
	if (n == 'F')
		return;
	node* l = new node();
	node* r = new node();
	l->num = (n ++);
	r->num = (n ++);
	head->left = l;
	head->right = r;
	creatT(head->left);
	creatT(head->right);
}

int main()
{
	node* tree = new node();
	tree->num = 'A';
	node* head = tree;
	creatT(tree);
	mid(tree);
	pre(tree);
	beh(tree);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值