二叉树的前、中、后遍历

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

struct node{
	int val;
	struct node* left;
	struct node* right;
	bool is_first;
	node(int x):val(x),left(NULL),right(NULL),is_first(true){
	}
};

void pre(node* head)
{
	if (head!=NULL)
	{
		cout<<head->val<<" ";
		pre(head->left);
		pre(head->right);
	}
}

void pre2(node* head)
{
	stack<node* >s;
	node* p = head;
	while (p!=nullptr || !s.empty())    //注意初始条件。 || 
	{
		while (p!=nullptr)
		{
			cout<<p->val<<" ";  //1、访问 
			s.push(p);         //2、入栈 
			p = p->left;         // 左 
		}  
		
		if (!s.empty())
		{
			p = s.top();      //将当前节点扔掉,因为以及访问过,而且其左孩子为空。 
			s.pop();
			p = p->right;     // 右 
		}
		
	}
}

void in_order(node* head) 
{
	if (head)
	{
		in_order(head->left);
		cout<<head->val<<" ";
		in_order(head->right);
	}
}

void in_order2(node* head)
{
	node* p = head;
	stack<node* >s;
	while (p!=nullptr || !s.empty())
	{
		while(p!=nullptr)
		{
			s.push(p);
			p = p->left;
		}
		if (!s.empty())
		{
			p = s.top();
			cout<<p->val<<" ";
			s.pop();
			p = p->right;
		}
	}
}

void post_order(node* head)
{
	if(head) 
	{
		post_order(head->left);
		post_order(head->right);
		cout<<head->val<<" ";
	}
}

void post_order2(node* head) 
{
	node* p = head;
	stack<node* >s;
	while (p!=nullptr || !s.empty())
	{
		while (p!=nullptr)
		{
			s.push(p);
			p = p->left;
		}
		if (!s.empty())
		{
			p = s.top();
			s.pop();
			if (!(p->is_first))   //第二次出现 
			{
				cout<<p->val<<" ";
				p = NULL;
			}
			else
			{
				p->is_first = false;
				s.push(p);       // 第一次出现的化,再次压入,确保右孩子为 NULL 
				p = p->right;
			}
			
		}
	}
}

int main()
{
	struct node* p = new node(1);
	
	p->left = new node(2); p->left->left = new node(4); p->left->left->right = new node(6); 
	p->left->left->right->left = new node(7); p->left->left->right->right = new node(8);
	
	p->right = new node(3); p->right->right = new node(5);
	
	
//	pre(p);
//	pre2(p);
//	in_order(p);
//	in_order2(p);
//	post_order(p);
	post_order2(p);
	
	return 0;
}

参考:https://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html
https://www.jianshu.com/p/456af5480cee

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值