Convert BST to double linked lists in order

#include <iostream>
#include <cstdlib>
struct BSTNode{
  int v;
  struct BSTNode *left,*right;
};

struct BSTNode *root=NULL,*head=NULL,*tail=NULL;

struct BSTNode* createNode(int data){
    struct BSTNode *newNode;
    newNode=(struct BSTNode*)malloc(sizeof(struct BSTNode));
    newNode->v=data;
    newNode->left=NULL;
    newNode->right=NULL;
    return newNode;
}

void insertion(struct BSTNode **node,int data){
    if(*node==NULL){
        *node=createNode(data);
    }else if(data<(*node)->v){
            insertion(&(*node)->left,data);
        }else if(data>(*node)->v){
            insertion(&(*node)->right,data);
        }
}
void traverse(struct BSTNode *node){
    if(node!=NULL){
        traverse(node->left);
        std::cout<<node->v;
        traverse(node->right);
    }
    return;
}

void helper(struct BSTNode **h, struct BSTNode **t, struct BSTNode *root){
    BSTNode *lt=NULL,*rh=NULL;
    if(root==NULL){
        *h=NULL;*t=NULL;
        return;
    }
    helper(h,&lt,root->left);
    helper(&rh,t,root->right);
    if(lt!=NULL){
        lt->right=root;
        root->left=lt;
    }else{
        *h=root;
    }
    if(rh!=NULL){
        root->right=rh;
        rh->left=root;
    }else{
        *t=root;
    }
}

int main(){
    int data,ch;
    insertion(&root,10);
    insertion(&root,16);
    insertion(&root,8);
    insertion(&root,20);
    insertion(&root,21);
    traverse(root);
    helper(&head,&tail,root);
    std::cout<<head->right->v;
    std::cin>>data;
}

 

posted @ 2014-01-04 17:42  丸子No1  阅读(181)  评论(0编辑  收藏  举报