描述
Given a binary tree, return the inorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Given a binary tree, return the inorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
#include "BinaryTree.h"
#include <stack>
#include<vector>
using namespace std;
//===二叉树的中序遍历,递归版本
void MidorderTraversal(BinaryTreeNode *proot)
{
if (proot)
{
if (proot->m_pLeft)
MidorderTraversal(proot->m_pLeft);
cout << proot->m_nValue << " ";
if (proot->m_pRight)
MidorderTraversal(proot->m_pRight);
}
}
//===二叉树的中序遍历,迭代版本
void MidorderTraversal2(BinaryTreeNode *proot)
{
stack<BinaryTreeNode*> temp;
vector<int> cahe;
BinaryTreeNode *p = proot;
while ((!temp.empty())||p!=NULL)
{
while (p)
{
temp.push(p);
p = p->m_pLeft;
}
if (!temp.empty())
{
p = temp.top();
temp.pop();
cahe.push_back(p->m_nValue);
p = p->m_pRight;
}
}
//======
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);
//===
MidorderTraversal(pNode8);
cout << endl;
//===
MidorderTraversal2(pNode8);
//==
DestroyTree(pNode8);
}