非递归后序遍历二叉树

后序遍历二叉树(递归)


void postOrder(BT* root) {
	if (root == NULL)
		return;

	postOrder(root->lchild);
	postOrder(root->rchild);

	cout << "Node " << root->num
		<< " 's text is " << root->text << endl;
}

后序遍历二叉树(非递归)

记录一下后序遍历非递归写法的步骤:

  1. 将头结点压入栈;
  2. 弹出栈顶元素并压入另一个栈;
  3. 将弹出元素的孩子压入当前栈,先左孩子再右孩子;
  4. 重复2、3.

void postOrder_stack(BT* root) {
	if (root == NULL)
		return;

	stack<BT*> post1;
	stack<BT*> post2;

	//将树以 根右左 的顺序压入第二个栈
	post1.push(root);
	while (!post1.empty()) {
		root = post1.top();
		post1.pop();

		post2.push(root);

		if (root->lchild != NULL)
			post1.push(root->lchild);

		if (root->rchild != NULL)
			post1.push(root->rchild);
	}

	//将第二个栈内的元素一一输出,输出后即是后序排列
	while (!post2.empty()) {
		root = post2.top();
		cout << "Node " << root->num
			<< " 's text is " << root->text << endl;
		post2.pop();
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值