分享

把二元查找树转变成排序的双向链表

 看风景D人 2014-01-08
#include<iostream>
using namespace std;
  
struct BSTreeNode {
    int m_nValue;
    BSTreeNode * m_pLeft;
    BSTreeNode * m_pRight;
    BSTreeNode(int value){
        m_nValue = value;
        m_pLeft = NULL;
        m_pRight = NULL;
    }
};
  
BSTreeNode * BSTreeNodeList[7];
  
BSTreeNode * buildTestTree() {
    int values [7] = {10,6,14,4,8,12,16};
    for(int i=0;i<sizeof(values)/sizeof(int);i++){
        BSTreeNodeList[i] = new BSTreeNode(values[i]);
    }
    BSTreeNode * root = BSTreeNodeList[0];
    root->m_pLeft = BSTreeNodeList[1];
    root->m_pRight = BSTreeNodeList[2];
  
    BSTreeNodeList[1]->m_pLeft = BSTreeNodeList[3];
    BSTreeNodeList[1]->m_pRight = BSTreeNodeList[4];
  
    BSTreeNodeList[2]->m_pLeft = BSTreeNodeList[5];
    BSTreeNodeList[2]->m_pRight = BSTreeNodeList[6];
  
    return root;
}
  
BSTreeNode * tail = NULL;
BSTreeNode * head = NULL;
  
void scan(BSTreeNode * root) {
    if (root == NULL) return ;
    scan(root->m_pLeft);
    if(tail == NULL) head = root;
    root->m_pLeft = tail;
    if (tail != NULL) tail->m_pRight = root;
    tail = root;
    scan(root->m_pRight);
}
  
int main(){
    BSTreeNode * root = buildTestTree();
    scan(root);
    BSTreeNode * p = head;
    while(p!=NULL){
        cout<<p->m_nValue<<endl;
        p = p->m_pRight;
    }
    cout<<"------------"<<endl;
    p = tail;
    while(p!=NULL){
        cout<<p->m_nValue<<endl;
        p = p->m_pLeft;
    }
    return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多