算法导论 12-1-3 中序遍历的非递归算法

题目:设计一个中序遍历的非递归算法

思路:参照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);
        }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值