题目:设计一个中序遍历的非递归算法
思路:参照10-4-5节的思路,这一次换了一种写法,思路和之前的还是差不多。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct TreeNode
{
int key;
struct TreeNode * parent;
struct TreeNode * left;
struct TreeNode * right;
TreeNode()
{
parent = NULL;
left = NULL;
right = NULL;
}
};
TreeNode* createTree(TreeNode * root,int d);
void printTreeM(TreeNode * root);
void printTreeNo(TreeNode * root);
int main ()
{
TreeNode*root = 0;
srand(time(NULL));
int n = 13;
for (int i = 0;i < n;i ++)
{
root = createTree(root,rand());
}
// printTreeF(root);
cout <<endl;
printTreeM(root);
cout << endl;
printTreeNo(root);
// printTreeNONRECURiSION(root);
}
TreeNode* createTree(TreeNode * root,int d)
{
struct TreeNode * tmp = new struct TreeNode();
tmp->key = d;
if (NULL == root)
{
root = tmp;
return root;
}
else
{
struct TreeNode* p = NULL;
struct TreeNode* q = NULL;
p = root;
while (p != NULL)
{
q = p;
if (d < p->key )
{
p = p->left;
}
else
{
p = p->right;
}
}
if (d < q->key)
{
q->left = tmp;
tmp->parent =q;
}
else if ( d > q->key)
{
q->right = tmp;
tmp->parent =q;
}
else
{
delete tmp;
}
return root;
}
}
void printTreeM(TreeNode * root)
{
if (NULL == root)
return;
printTreeM(root->left);
cout << root->key << '\t';
printTreeM(root->right);
}
void printTreeNo(TreeNode * p)
{
TreeNode * x = NULL;
while (p != NULL)
{
if (x != p->left)
{
p = p->left;
continue;
}
cout << p->key << ' ';
if (p->right)
{
x = NULL;
p = p->right;
}
else
{
do
{
x = p;
p = p->parent;
}while(p && x == p->right);
}
}
}