0
点赞
收藏
分享

微信扫一扫

非递归后序遍历二叉树

我阿霆哥 2022-03-14 阅读 70

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();
	}
	
}

举报

相关推荐

0 条评论