描述
Given a binary tree, return the postorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
Given a binary tree, return the postorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
#include "BinaryTree.h"
#include <stack>
#include<vector>
using namespace std;
//===二叉树的后序遍历,递归版本
void PostorderTraversal(BinaryTreeNode *proot)
{
if (proot)
{
if (proot->m_pLeft)
PostorderTraversal(proot->m_pLeft);
if (proot->m_pRight)
PostorderTraversal(proot->m_pRight);
cout << proot->m_nValue << " ";
}
}
//===二叉树的后序遍历,迭代版本
void PostorderTraversal2(BinaryTreeNode *proot)
{
stack<BinaryTreeNode*> temp;
vector<int> cahe;
BinaryTreeNode *p = proot,*q;
bool flag;
do
{
while (p)
{
temp.push(p);
p = p->m_pLeft;
}
flag = true;
q = NULL;
while ((!temp.empty()) && flag)
{
p = temp.top();
if (p->m_pRight == q)
{
cahe.push_back(p->m_nValue);
temp.pop();
q = p;
}
else
{
p = p->m_pRight;
flag = false;
}
}
} while (!temp.empty());
//======
for (int i = 0; i < cahe.size(); i++)
cout << cahe[i] << " ";
cout << endl;
}
// ====================测试代码====================
// 8
// 6 10
// 5 7 9 11
int main()
{
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);
ConnectTreeNodes(pNode8, pNode6, pNode10);
ConnectTreeNodes(pNode6, pNode5, pNode7);
ConnectTreeNodes(pNode10, pNode9, pNode11);
//===
//PrintTree(pNode8);
//===
PostorderTraversal(pNode8);
cout << endl;
//===
PostorderTraversal2(pNode8);
//==
DestroyTree(pNode8);
}