C++ 二叉树非递归遍历(别贪心,一次循环访问一个节点,前序遍历2例外)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25244495/article/details/83477967

前序遍历方法1:

void preOrder1(BiNode * rootN)
{
	if (rootN != nullptr)
	{
		stack<BiNode*> nodeSta;
		nodeSta.push(rootN);
		BiNode* curNode;
		while(!nodeSta.empty())
		{
			curNode = nodeSta.top();
			nodeSta.pop();
			cout << curNode->val << " ";
			if(curNode->right != nullptr)
				nodeSta.push(curNode->right);
			if(curNode->left != nullptr)
				nodeSta.push(curNode->left);
		}
	}
	cout << endl;
}

前序遍历方法2:

void preOrder2(BiNode* rootN)
{
	stack<BiNode*> nodeSta;
	BiNode* curNode = rootN;
	while(!nodeSta.empty() || curNode != nullptr)
	{
		while(curNode)
		{
			cout << curNode->val << " ";
			nodeSta.push(curNode);
			curNode = curNode->left;
		}

		if (!nodeSta.empty())
		{
			curNode = nodeSta.top();
			nodeSta.pop();
			curNode = curNode->right;
		}
	}
	cout << endl;
}

中序遍历:

void inOrder1(BiNode* rootN)
{
	stack<BiNode*> nodeSta;
	BiNode* curNode = rootN;
	while(curNode || !nodeSta.empty())
	{
		while(curNode)
		{
			nodeSta.push(curNode);
			curNode = curNode->left;
		}

		curNode = nodeSta.top();
		nodeSta.pop();
		cout << curNode->val << " ";

		curNode = curNode->right;

	}
	cout << endl;
}

后序遍历方法1(单栈):

void postOrder1(BiNode* rootN)
{
	BiNode *preNode = nullptr;//上一次打印的节点
	BiNode *curNode = rootN;
	stack<BiNode*> nodeSta;
	while(curNode || !nodeSta.empty())
	{
		while(curNode)
		{
			nodeSta.push(curNode);
			curNode = curNode->left;
		}

		BiNode *topNode = nodeSta.top();
		
		//如果结点的右孩子为空,或者右孩子已经被打印,则可以打印本结点
		if (topNode->right == nullptr || preNode == topNode->right)
		{
			cout << topNode->val << " ";//任一个节点都是被假想成根节点打印的
			nodeSta.pop();
			preNode = topNode;//注意 不要给curNode赋值,它就该为nullptr
		}
		else
			curNode = topNode->right;
	}
	cout << endl;
}

后序遍历方法2(双栈):

void postOrder2(BiNode* rootN)
{
	stack<BiNode*> nodeSta1,nodeSta2;
	BiNode* curNode = rootN;
	nodeSta1.push(rootN);
	while(!nodeSta1.empty())
	{
		curNode = nodeSta1.top();
		nodeSta1.pop();
		nodeSta2.push(curNode);
		if(curNode->left) nodeSta1.push(curNode->left);
		if(curNode->right) nodeSta1.push(curNode->right);
	}
	while(!nodeSta2.empty())
	{
		curNode = nodeSta2.top();
		nodeSta2.pop();
		cout << curNode->val << " ";
	}
	cout << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_25244495/article/details/83477967