1. 程式人生 > >C++ 二叉樹非遞迴遍歷(別貪心,一次迴圈訪問一個節點,前序遍歷2例外)

C++ 二叉樹非遞迴遍歷(別貪心,一次迴圈訪問一個節點,前序遍歷2例外)

前序遍歷方法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;
}