二叉树非递归遍历

#include<iostream>
#include<stack>
#include<vector>
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) { val = x; left = nullptr; right = nullptr; };
};
using namespace std;
//二叉树前序非递归遍历
void preOrder(TreeNode * root) {
	stack<TreeNode*> s;
	while (root !=nullptr || !s.empty())
	{
		while(root!=nullptr){
			cout << " " << root->val;
			s.push(root);
			root = root->left;
		}
		if (!s.empty())
		{
			root = s.top();
			s.pop();
			root = root->right;

		}
	}
}

//非递归中序遍历
void inorder(TreeNode * root) {
	stack<TreeNode *> s;
	while (!s.empty() || root!=nullptr)
	{
		while(root !=nullptr){
			s.push(root);
			root = root->left;
		}
		if (!s.empty()) {
			root = s.top();
			cout << " " << root->val;
			s.pop();
			root= root->right;
		}
	}
}

//非递归后序遍历
void postOrder(TreeNode * root) {
	stack<TreeNode *> s;
	TreeNode *cur = root;
	TreeNode *pre = nullptr;
	while (cur!=nullptr || !s.empty())
	{
		while (cur !=nullptr)
		{
			s.push(cur);
			cur = cur->left;
		}
		if(!s.empty()){
			TreeNode* cur= s.top();
			if (cur->right == nullptr || pre == cur->right) {
				cout << " " << cur->val;
				pre = cur;
				cur = nullptr;
				s.pop();
			}else{
				cur = cur->right;
				while (cur)
				{
					s.push(cur);
					cur = cur->left;
				}
			}
		}

	}
}
TreeNode* makeTree() {
	TreeNode* root = nullptr;
	root=new TreeNode(1);
	TreeNode* node2 = new TreeNode(8);
	TreeNode* node3 = new TreeNode(3);
	TreeNode* node4 = new TreeNode(4);
	TreeNode* node5 = new TreeNode(5);
	TreeNode* node6 = new TreeNode(6);
	root->left = node2; root->right = node5;
	node2->left = node3; node2->right = node4;
	node5->left = node6;
	return root;
}
int main() {
	TreeNode * root = makeTree();
	cout << endl << "二叉树非递归前序遍历" << endl;
	preOrder(root);
	cout << endl << "二叉树非递归中序遍历" << endl;
	inorder(root);
	cout << endl << "二叉树非递归后序遍历" << endl;
	postOrder(root);
	return 0;
}
上一篇:二叉树的遍历


下一篇:刷题-力扣-111. 二叉树的最小深度