二叉树的非递归前序、中序、后序、层次遍历

1.前序非递归

/*非递归前序遍历*/
void PreOrderNonRecurive(TreeNode *root)
{
	if (!root) return;
	stack<TreeNode *> s;
	s.push(root);
	while (!s.empty())
	{
		TreeNode *temp = s.top();
		cout << temp->data << "";
		s.pop();
		if (temp->rchild) s.push(temp->rchild);  //栈是先进后出,所以右子树先入栈
		if (temp->lchild) s.push(temp->lchild);
	}
	cout << endl;
}

2.中序非递归

/*非递归中序遍历*/
void InOrderNonRecurive(TreeNode *root)
{
	if (!root) return;
	stack<TreeNode *> s;
	TreeNode *cur = root;
	while (!cur || !s.empty())
	{
		while (!cur)
		{
			//cout << cur->data << " ";  //如果是前序,输出放这
			s.push(cur);
			cur = cur->lchild;
		}
		if (!s.empty()) //此条件可以省略
		{
			cur = s.top();
			s.pop();
			cout << cur->data << " ";
			cur = cur->rchild;
		}
	}
	cout << endl;
}

注意:这种方法也适合于前序遍历,区别是前序遍历是在入栈的时候输出数据,而中序遍历是在出栈的时候输出数据。

3.后序非递归

方法一:标记前一个被访问的结点

/*非递归后序遍历*/
void PostOrderNonRecurive(TreeNode *root)
{
	if (!root) return;
	stack<TreeNode *> s;
	TreeNode *cur = root;
	TreeNode *preVisited = NULL;
	while (!cur || !s.empty())
	{
		while (!cur)
		{
			s.push(cur);
			cur = cur->lchild;
		}
		cur = s.top();
		if (!cur->rchild || cur->rchild == preVisited)
		{
			cout << cur->data << " ";
			s.pop();
			preVisited = cur;
			cur = NULL;  //目的是不让其进入上一个while循环,从而使cur重新入栈
		}
		else cur = cur->rchild;
	}
	cout << endl;
}
方法二:双栈法

void PostOrderNonRecurive_(TreeNode *root)
{
	if (!root) return;
	TreeNode *cur = root;
	stack<TreeNode *> s1, s2;
	s1.push(cur);
	while (!s1.empty())
	{
		cur = s1.top();
		s1.pop();
		s2.push(cur);
		if (cur->lchild) s1.push(cur->lchild);
		if (cur->rchild) s1.push(cur->rchild);
	}
	while (!s2.empty())
	{
		cout << s2.top()->data << " ";
		s2.pop();
	}
	cout << endl;
}


4.非递归层次遍历

void LevelOrder(TreeNode *root)
{
	TreeNode *cur = root;
	queue<TreeNode *> q;
	if (Visit(cur)) q.push(cur);
	else return;
	while (!q.empty())
	{
		cur = q.front();
		q.pop();
		if (Visit(cur->lchild)) q.push(cur->lchild);
		if (Visit(cur->lchild)) q.push(cur->rchild);
	}
	cout << endl;
}

5.树的深度

int Depth(TreeNode *root)
{
	if (!root) return 0;
	int d1 = Depth(root->lchild);
	int d2 = Depth(root->rchild);
	return (d1 > d2 ? d1 : d2) + 1;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值