二叉树系列——二叉树的定义以及各种遍历方式

二叉树的三种遍历的递归和非递归实现,代码如下:

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

//二叉树定义
struct BinaryTreeNode
{
	int m_nValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode*m_pRight;
};

//前序遍历,递归
void PreOrderRecur(BinaryTreeNode*pRoot,vector<int>& vecSeq){
	if (pRoot==NULL)
	{
		return;
	}
	cout << pRoot->m_nValue<<" ";
	vecSeq.push_back(pRoot->m_nValue);
	PreOrderRecur(pRoot->m_pLeft,vecSeq);
	PreOrderRecur(pRoot->m_pRight,vecSeq);
}
//前序遍历,非递归
void PreOrderUnRecur(BinaryTreeNode*head){
	if (head==NULL)
	{
		return;
	}
	//栈
	stack<BinaryTreeNode*> stackTemp;
	stackTemp.push(head);
	while (!stackTemp.empty())
	{
		BinaryTreeNode* temp = stackTemp.top();
		cout << temp->m_nValue;
		stackTemp.pop();
		if (temp->m_pRight!=NULL)
		{
			stackTemp.push(temp->m_pRight);
		}
		if (temp->m_pLeft!=NULL)
		{
			stackTemp.push(temp->m_pLeft);
		}
	}
}

//中序遍历,递归
void InOrderRecur(BinaryTreeNode*tree){
	if (tree==NULL)
	{
		return;
	}
	InOrderRecur(tree->m_pLeft);
	cout << tree->m_nValue;
	InOrderRecur(tree->m_pRight);
}
//中序遍历,非递归
void InOrderUnRecur(BinaryTreeNode*head){
	if (head==NULL)
	{
		return;
	}
	stack<BinaryTreeNode*> stackTemp;
	while (!stackTemp.empty()||head!=NULL)
	{
		if (head!=NULL)
		{
			stackTemp.push(head);
			head = head->m_pLeft;
		}
		else{
			BinaryTreeNode*temp = stackTemp.top();
			cout << temp->m_nValue;
			stackTemp.pop();
			head = head->m_pRight;
		}
	}
}

//后序遍历,递归
void PostOrderRecur(BinaryTreeNode*tree){
	if (tree==NULL)
	{
		return;
	}
	PostOrderRecur(tree->m_pLeft);
	PostOrderRecur(tree->m_pRight);
	cout << tree->m_nValue;
}
//后序遍历,非递归
void PostOrderUnRecur(BinaryTreeNode*pHead){
	if (pHead==NULL)
	{
		return;
	}
	stack<BinaryTreeNode*> stack1;
	stack<BinaryTreeNode*> stack2;
	stack1.push(pHead);
	while (!stack1.empty())
	{
		BinaryTreeNode*pTemp = stack1.top();
		stack2.push(pTemp);
		stack1.pop();
		if (pTemp->m_pLeft!=NULL)
		{
			stack1.push(pTemp->m_pLeft);
		}
		if (pTemp->m_pRight!=NULL)
		{
			stack1.push(pTemp->m_pRight);
		}
	}
	while (!stack2.empty())
	{
		cout << stack2.top()<<" ";
		stack2.pop();
	}
	cout << endl;
}

int main(){

	return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值