二叉树的遍历:前序非递归和中序非递归

二叉树的遍历:前序非递归和中序非递归

**

(一)先利用前序遍历创建二叉树

详情可以见文章二叉树创建和递归遍历
**
创建如图的二叉树
在这里插入图片描述程序运行后,在控制台输入如下:
ABDH##I##E##CF#J##G##
就可以创建好上图的二叉树

非递归遍历的算法如下:

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

typedef char datatype;

//二叉树的左右链表示,也叫做二叉链表表示
typedef struct node {
	datatype data;
	struct node* lchild;
	struct node* rchild;
}Node;

typedef Node* Btree;

Btree preCreateBT() {
	Btree T;
	char ch;
	cin >> ch;
	if (ch == '#') {
		T = NULL;
	}
	else {
		T = new node;
		T->data = ch;
		T->lchild = preCreateBT();
		T->rchild = preCreateBT();
	}
	return T;
}

//先序遍历
/*
void PreOrder(Btree BT) {
	if (BT != NULL) {
		cout << BT->data<<endl;
		PreOrder(BT->lchild);
		PreOrder(BT->rchild);
	}
}
*/

//中序遍历
/*
void InOrder(Btree BT) {
	if (BT != NULL) {
		InOrder(BT->lchild);
		cout << BT->data << endl;
		InOrder(BT->rchild);
	}
}
*/

//后序遍历
/*
void PostOrder(Btree BT) {
	if (BT != NULL) {
		PostOrder(BT->lchild);
		PostOrder(BT->rchild);
		cout << BT->data << endl;
	}
}
*/

//先序遍历非递归算法
/*
void PreOrderNoRecur(Btree root) {
	stack<Btree> S;
	while (root != NULL || !S.empty()) {
		while (root != NULL) {
			cout << root->data << endl;
			S.push(root);
			root = root->lchild;
		}

		if (!S.empty()) {
			root = S.top();
			S.pop();
			root = root->rchild;
		}
	}
}
*/

//中序遍历非递归算法
void InOrderNoRecur(Btree root) {
	stack<Btree> S;
	while (root != NULL || !S.empty()) {
		while (root != NULL) {
			S.push(root);
			root = root->lchild;
		}

		if (!S.empty()) {
			root = S.top();
			cout << root->data << endl;
			S.pop();
			root = root->rchild;
		}
	}
}

int main() {
	//前序遍历创建树
	Btree TreeOne = preCreateBT();
	
	//先序遍历(递归)
	//PreOrder(TreeOne);

	//中序遍历(递归)
	//InOrder(TreeOne);

	//后序遍历(递归)
	//PostOrder(TreeOne);

	//先序遍历非递归算法
	//PreOrderNoRecur(TreeOne);

	//中序遍历非递归算法
	InOrderNoRecur(TreeOne);
	
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值