二叉树的三种遍历方式:递归、栈、循环

本文介绍了二叉树的三种遍历方法,包括递归、栈辅助和循环实现。递归方法直观但可能导致栈溢出,栈方法需要额外空间,循环实现则相对复杂。
摘要由CSDN通过智能技术生成

          三种方法中,递归最为简单,栈次之,循环最为麻烦。递归的深度如果太大则会导致栈溢出;栈的方式需要额外的辅助空间;循环编程最麻烦。

          首先是递归:

//递归方法
void midPrint_r(TreeNode* root)
{//中序遍历
	if(root==NULL)
		return;
	if(root->left)
		midPrint_r(root->left);
	cout<<root->val<<"   ";
	if(root->right)
		midPrint_r(root->right);
}

void prePrint_r(TreeNode* root)
{//前序遍历
	if(root==NULL)
		return;
	cout<<root->val<<"   ";
	if(root->left)
		prePrint_r(root->left);	
	if(root->right)
		prePrint_r(root->right);
}

void postPrint_r(TreeNode* root)
{//中序遍历
	if(root==NULL)
		return;
	if(root->left)
		postPrint_r(root->left);	
	if(root->right)
		postPrint_r(root->right);
	cout<<root->val<<"   ";
}

    栈方法:先循环把结点压入到栈中,然后再逐个弹出;

//循环堆栈方法
void midPrint_l(TreeNode* root)
{
	stack<TreeNode*> s;
	TreeNode *cur = root;
	while(!s.empty() || cur != NULL)
	{
		while(cur != NULL)
		{
			s.push(cur);
			cur = cur->left;
		}
		cur = s.top();
		s.pop();
		cout<<cur->val<<" ";
		cur = cur->right;
	}
}

void prePrint_l(TreeNode* root)
{
	stack<TreeNode*> s;
	TreeNode *cur = root;
	while(!s.empty() || cur != NULL)
	{
		while(cur != NU
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值