二叉树先序、中序、后续、广度非递归遍历

 重点:非递归中序遍历,其他相对较简单


#include "Binary_Tree_Traversa.h"
#include <stack>
#include <queue>
#include <iostream>
using namespace std;

//用一个栈,有右放右,有左放左
void Binary_Tree_Traversa::preorder_non_recursive(TreeNode * root)
{
	if (root == nullptr)
		return;

	stack<TreeNode*>stack1;
	stack1.push(root);

	while (!stack1.empty())
	{
		TreeNode* temp = stack1.top();
		cout << temp->val << " ";
		stack1.pop();

		if (temp->rchild != nullptr)
		{
			stack1.push(temp->rchild);
		}
		if (temp->lchild != nullptr)
		{
			stack1.push(temp->lchild);
		}
	}
}

//用一个栈和一个指针,关键点在指针,也是难点
//放入栈的节点是一只放左节点,放到左节点指向空;
//再从栈中弹出一个节点,打印,并指向右节点。
void Binary_Tree_Traversa::inoder_non_recursive(TreeNode * root)
{
	if (root == nullptr)
		return;

	TreeNode* p = root;
	stack<TreeNode*>stack1;

	while (p != nullptr || !stack1.empty()) //注意点
	{
		while (p != nullptr)
		{
			stack1.push(p);
			p = p->lchild;
		}

		if (!stack1.empty())
		{
			p = stack1.top();
			cout << p->val << " ";
			stack1.pop();
			p = p->rchild;	//注意点
		}
	}
}

//参考先序非递归遍历:中左右
//后续:左右中    中左右-->中右左-->左右中
//用一个栈得到中右左,用另一个栈得到左右中
void Binary_Tree_Traversa::postorder_non_recursive(TreeNode * root)
{
	if (root == nullptr)
		return;

	stack<TreeNode*>stack1;
	stack<TreeNode*>stack2;
	stack1.push(root);

	while (!stack1.empty())
	{
		TreeNode* temp = stack1.top();
		stack2.push(temp);
		//cout << temp->val << " ";
		stack1.pop();

		if (temp->lchild != nullptr)
		{
			stack1.push(temp->lchild);
		}
		if (temp->rchild != nullptr)
		{
			stack1.push(temp->rchild);
		}

	}

	while (!stack2.empty())
	{
		cout << stack2.top()->val << " ";
		stack2.pop();
	}

}

//队列实现即可
void Binary_Tree_Traversa::broadorder(TreeNode * root)
{
	if (root == nullptr)
		return;

	queue<TreeNode*>queue1;
	queue1.push(root);

	while (!queue1.empty())
	{
		TreeNode* temp = queue1.front();
		cout << temp->val << " ";
		queue1.pop();

		if (temp->lchild != nullptr)
		{
			queue1.push(temp->lchild);
		}
		if (temp->rchild != nullptr)
		{
			queue1.push(temp->rchild);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_33457548/article/details/98079565