数据结构——二叉树前序中序后续的递归、非递归遍历

作者:小 琛
欢迎转载,请标明出处

因为二叉树是最基本的数据结构,解法也比较简单,这里就不做过多的讲解,直接上代码

#pragma once
#include <iostream>
#include <stack>
using namespace std;

template <class T>
struct BinaryNode
{
	struct BinaryNode* _left;
	struct BinaryNode* _right;
	struct BinaryNode* _parent;
	T _date;
};
template <class T>
class Binary
{
public:
	typedef  BinaryNode Node;
	void BinaryTree_OrderTraver(Node* root = _root)
	{
		stack<Node*> st;//定义一个栈
		Node* cur = root;//定义一个临时变量
		
		while (!st.empty()||cur)//当栈不为空或cur不为nullptr
		{
			while (cur)//执行对左树的打印
		{
			cout << root->_date << "  ";
			st.push(cur);//打印完成后入栈
			cur = cur->_left;//先序打印左树
		}
			cur = st.top();//拿出打印过的节点作为新的根
			cur = cur->_right;//对其右树进行相同操作
			st.pop();//出栈
		}
	}
	void BinaryTree_middleTraver(Node* root=_root)
	{
		stack<Node*> st;
		Node* cur = root;
		while (cur || !st.empty())
		{
			while (cur)
			{
				st.push(cur);
				cur = cur->_left;
			}
			cur = st.top();
			cout << cur->_date << "  ";
			cur = cur->_right;
		}
	}
	void BinaryTree_LastTraver(Node* root=_root)
	{
		stack<Node*> st;
		Node* cur = root;
		Node* prev = nullptr;
		while (cur || !st.empty())
		{
			while (cur)
			{
				st.push(cur);
				cur = cur->_left;
			}
			cur = st.top();
			if (cur->_right == nullptr || cur->_right == prev)
			{
				cout << cur->_date << "  ";
				prev = cur;
				st.pop();
			}
			else
			{
				cur = cur->_right;
			}
		}
	}
	void BinaryTree_OrderTraver_recursion(Node* root=_root)
	{
		Node* cur = root;
		if(cur != nullptr)
		{
			cout << cur->_date << "  ";
			BinaryTree_OrderTraver_recursion(cur->_left);
			BinaryTree_OrderTraver_recursion(cur->_right);
		}
	}
	void BinaryTree_middleTraver_recursion(Node* root=_root)
	{
		Node* cur = root;
		if(cur != nullptr)
		{
			BinaryTree_OrderTraver_recursion(cur->_left);
			cout << cur->_date << "  ";
			BinaryTree_OrderTraver_recursion(cur->_right);
		}
	}
	void BinaryTree_LastTraver_recursion(Node* root=_root)
	{
		Node* cur = root;
		if(cur != nullptr)
		{
			BinaryTree_OrderTraver_recursion(cur->_left);
			BinaryTree_OrderTraver_recursion(cur->_right);
			cout << cur->_date << "  ";
		}
	}
private:
	Node* _root;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值