题目要求:
实现二叉搜索树的前序、中序、后序非递归遍历。
题目分析:
非递归前序遍历:使用一个辅助栈,出栈一个结点并输出该结点,同时依次入栈该结点的右结点和左结点,再出栈,入栈...;
非递归中序遍历:使用一个辅助栈和一个临时结点,临时结点不断找树的左子树,知道为空,然后又跳到空结点父结点的右子树,又继续找右子树的左子树;
非递归后序遍历:使用两个辅助栈。
代码实现:
#include <iostream>
#include <stack>
using namespace std;
typedef struct BinaryTree
{
struct BinaryTree *left,*right;
int data;
}BinaryTree;
void initTree(BinaryTree **p);
void PreOrderTree(BinaryTree *p);
void InOrderTree(BinaryTree *p);
void PostOrderTreeTraversal(BinaryTree *p);
int main(void)
{
BinaryTree *root;
initTree(&root);
PreOrderTree(root);
InOrderTree(root);
PostOrderTreeTraversal(root);
return 0;
}
void PreOrderTree(BinaryTree *p)
{
stack<BinaryTree *> s;
s.push(p);
cout << "二叉搜索树的非递归前序遍历为:";
while(!s.empty())
{
BinaryTree *tmp = s.top();
cout << tmp->data << " ";
s.pop();
if(tmp->right)
s.push(tmp->right);
if(tmp->left)
s.push(tmp->left);
}
cout << endl;
}
void InOrderTree(BinaryTree *p)
{
stack<BinaryTree *> s;
BinaryTree *cur = p;
cout << "二叉搜索树的非递归中序遍历为:";
while(!s.empty() || cur!=NULL)
{
if(cur!=NULL)
{
s.push(cur);
cur = cur->left;
}
else
{
cur = s.top();
s.pop();
cout << cur->data << " ";
cur = cur->right;
}
}
cout << endl;
}
void PostOrderTreeTraversal(BinaryTree *p)
{
stack<BinaryTree *> sTraversal,sVisit;
sTraversal.push(p);
while(!sTraversal.empty())
{
BinaryTree *tmp = sTraversal.top();
sTraversal.pop();
sVisit.push(tmp);
if(tmp->left)
sTraversal.push(tmp->left);
if(tmp->right)
sTraversal.push(tmp->right);
}
cout << "二叉搜索树的非递归后序遍历:";
while(!sVisit.empty())
{
cout << sVisit.top()->data << " ";
sVisit.pop();
}
cout << endl;
}
// 10
// / \
// 5 12
// / \
// 4 7
void initTree(BinaryTree **p)
{
*p = new BinaryTree;
(*p)->data = 10;
BinaryTree *tmpNode = new BinaryTree;
tmpNode->data = 5;
(*p)->left = tmpNode;
tmpNode = new BinaryTree;
tmpNode->data = 12;
(*p)->right = tmpNode;
tmpNode->left = NULL;
tmpNode->right = NULL;
BinaryTree *currentNode = (*p)->left;
tmpNode = new BinaryTree;
tmpNode->data = 4;
currentNode->left = tmpNode;
tmpNode->left = NULL;
tmpNode->right = NULL;
tmpNode = new BinaryTree;
tmpNode->data = 7;
currentNode->right = tmpNode;
tmpNode->left = NULL;
tmpNode->right = NULL;
cout << "二叉搜索树为:" <<endl;
cout << " " << 10<<endl;
cout << " " <<"/" << " "<< "\\" <<endl;
cout << " " << 5 << " " << 12 << endl;
cout << " " <<"/" << " "<< "\\" <<endl;
cout << 4 << " " << 7 << endl;
}