关于二叉树的前中后序遍历的非递归写法

#include
#include
using namespace std;
struct TreeNode
{
	int val;
	TreeNode *lchild;
	TreeNode *rchild;
};
void perOrder(TreeNode &root)
{
	stack st;
	
	TreeNode *cur = &root;
	while (cur != nullptr)
	{
		cout << cur->val << " ";
		if (cur->rchild != nullptr)
		{
			st.push(cur->rchild);
		}
		if (cur->lchild != nullptr)
		{
			st.push(cur->lchild);
		}
		if (st.empty())
			break;
		cur = st.top();
		st.pop();
	}
}


void InOrder(TreeNode &root)
{
	stack st;

	TreeNode *cur = &root;
	while (!st.empty()||cur != nullptr)
	{
		if (cur != nullptr)
		{
			st.push(cur);
			cur = cur->lchild;
		}
		else
		{
			cur = st.top();
			st.pop();
			cout << cur->val << " ";
			cur = cur->rchild;
		}
	}
}
void postOrder(TreeNode &root)
{
	stack st;
	stack stt;

	TreeNode *cur = &root;
	while (cur != nullptr)
	{
		stt.push(cur);
		
		if (cur->lchild != nullptr)
		{
			st.push(cur->lchild);
		}
		if (cur->rchild != nullptr)
		{
			st.push(cur->rchild);
		}
		if (st.empty())
			break;
		cur = st.top();
		st.pop();
	}

	while (!stt.empty())
	{
		cout << stt.top()->val << " ";
		stt.pop();
	}
}
int main()
{
	TreeNode t[5];
	for (int i = 0; i < 5; ++i)
	{
		t[i].val = i + 1;
		t[i].lchild = nullptr;
		t[i].rchild = nullptr;
	}

	t[0].lchild = &t[1];
	t[0].rchild = &t[2];
	t[1].lchild = &t[3];
	t[1].rchild = &t[4];
	//t[2].lchild = &t[5];

	//po(&t[0]);
	perOrder(t[0]);
	cout << endl;
	InOrder(t[0]);
	cout << endl;
	postOrder(t[0]);
	return 0;
}



 

你可能感兴趣的:(算法,数据结构)