C++二叉树非递归后序遍历

#include<iostream>
#include<stdlib.h> 
#include<stack>

using namespace std;

typedef struct treenode
{
	char data;
	treenode *right;
	treenode *left;
}*Node;

typedef struct node {
	treenode *t;
	int tag;   //分别表示左右子女被访问
};

//创建二叉树
void creat_tree(treenode *&rt)
{
	char ch;
	ch = getchar();
	if ('#' == ch) {
		rt = NULL;
	} else {
		rt = new treenode;
		rt->data = ch;
		creat_tree(rt->left);        //构造左子树
		creat_tree(rt->right);    //构造右子树    
	}
}

//非递归的后序遍历
void Back(treenode *root) {
	stack <node> s;
	while (root != NULL || !s.empty()) {  //根节点非空,栈非空
		while (root != NULL) {
			node a;
			a.t = root;
			a.tag = 0;
			s.push(a);
			root = root->left;
		}

		while (!s.empty() && s.top().tag == 1) {
			cout << s.top().t->data << " ";  //输出数据
			s.pop();  //出栈
		}

		if (!s.empty()) {
			s.top().tag = 1;
			root = s.top().t->right;
		}
	}

}

void Delete(treenode *&root) {  //必须删除,释放空间,后续遍历删除
	if (root) {
		Delete(root->left);
		Delete(root->right);
		delete root;
	}

}

int main() {
	treenode *root = NULL;
	int height, width;  //表示高度和最大宽度
	cout << "请输入二叉树,空值以#代表:" << endl;
	creat_tree(root);        //创建二叉树

	Back(root);  //后续遍历
	Delete(root);  //释放空间

	system("pause");
	return 0;
}



/*
ABD##E##CF###
ABD##E##C#F##
AB#CD##EF####
*/

    原文作者:coolsunxu
    原文地址: https://blog.csdn.net/coolsunxu/article/details/80383560
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞