中序线索二叉树

注意指针作为实参时传递的也是副本,若要修改指针则必须使用指针的指针或指针的引用

#include <iostream>

#include "conio.h"// 提供getch()设置断点
using namespace std;
typedef struct btnode{
        int value;
        int ltag,rtag;
        struct btnode *lchild;
        struct btnode *rchild;
        }btnode;


void createtree(btnode *&, int);
//void preorder(btnode *);
void inthreadtree(btnode *&,btnode *&);
void tra(btnode*);
btnode* first(btnode*);
btnode* next(btnode*);


int main(void)
{
    btnode* root = new btnode;
    int n;


    cin>>n;
    root->value = n;
    root->ltag = 0; root->rtag = 0;
    root->lchild = NULL;
    root->rchild = NULL;
    
    while(cin>>n) 
    createtree(root, n);


   // preorder(root);


    btnode* pre = NULL;
    inthreadtree(root, pre);//传的只是指针的副本  pre也是副本导致线索并没有被连起来 
    tra(root);


return 0;    
}


void createtree(btnode*& root, int n)
{    
if(root != NULL) {
if(n < root->value) {
             
createtree(root->lchild, n);
        }
else
createtree(root->rchild, n);
}
else {
        root = new btnode; 
root->value = n;
root->ltag = 0; root->rtag = 0;
root->lchild = NULL;
root->rchild = NULL;
}
}


/*void preorder(btnode* root)
{
if(root != NULL) {
cout<<root->value<<endl;
preorder(root->lchild);
preorder(root->rchild);
}
}*/


void inthreadtree(btnode*& root,btnode*& pre)
{
      if(NULL != root) {
              inthreadtree(root->lchild, pre);
                  if(NULL == pre) {
                          root->ltag = 1;
                          root->lchild = NULL;          
                  }else {
                          if(pre->rchild == NULL) {
                                         pre->rtag = 1;
                                         pre->rchild = root;               
                          }
                          if(root->lchild == NULL) {
                                          root->ltag = 1;
                                          root->lchild = pre;               
                          }
                        }
                  pre = root;
              inthreadtree(root->rchild, pre);
      }    
}
void tra(btnode* root)
{
    
     btnode* p = first(root);
     while(NULL != p) {
                cout<<p->value<<",";
                p = next(p);                        
     }
}


btnode* first(btnode* root)
{
        while(root->lchild != NULL && root->ltag == 0) root = root->lchild;      
        return root;
}   


btnode* next(btnode* root)
{
        if(root->rchild != NULL && root->rtag == 1) return root->rchild; 
        else return first(root->rchild);        
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值