元查找树转双向链表

来源:互联网 发布:qq飞车幻灵奇迹数据 编辑:程序博客网 时间:2024/06/16 10:36
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
    要求不能创建任何新的结点,只调整指针的指向。
      10
      / \
     6 14
     / \ / \
    4 8 12 16
    转换成双向链表
    4=6=8=10=12=14=16。
    首先我们定义的二元查找树 节点的数据结构如下:
    struct BSTreeNode
    {
        int m_nValue; // value of node
        BSTreeNode *m_pLeft; // left child of node
        BSTreeNode *m_pRight; // right child of node

    }; 


分析:二元查找树转成双向链表后链表的顺序同二元查找树的中序遍历顺序一样。因此,可以采用中序遍历的方式来生成双向链表。

BSTNode *BSTtoDulist(BSTNode *bst){    stack<BSTNode *> my_stack;    BSTNode * pre_node = NULL;    BSTNode * curr_node = bst;    BSTNode * dulistHead = NULL;    while(curr_node!=NULL || !my_stack.empty()) {        if(NULL!=curr_node) {            my_stack.push(curr_node);            curr_node = curr_node->left;        }        else {            curr_node = my_stack.top();            my_stack.pop();            if(NULL!=pre_node)               pre_node->right = curr_node;            else{               dulistHead = curr_node;            }            curr_node->left = pre_node;            pre_node=curr_node;            curr_node=curr_node->right;        }    }   return dulistHead;}



0 0
原创粉丝点击