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

来源:互联网 发布:2017最新网络推广渠道 编辑:程序博客网 时间:2024/06/15 10:13

题目:

输入一颗二元查找树,将该二元查找树转换成一个排序的双向链表。

要求不能创建任何新的节点,只调整指针的指向。

例如                                                    10

                                                            /  \

                                                         6    14

                                                        / \      /  \

                                                     4   8   12  16

                        转换成双向链表: 4=6=8=10=12=14=16


递归方法

递归函数返回二元查找树转换后的双向链表的首尾指针,先转换节点的两棵子树,然后再将两棵子树转换得到的两个双向链表通过该节点连接起来。

#include<iostream>using namespace std;struct BSTreeNode{    int m_nValue;    BSTreeNode *m_pLeft;    BSTreeNode *m_pRight;};typedef pair<BSTreeNode*, BSTreeNode*> HeadandTail;HeadandTail BSTreeToDlist(BSTreeNode *root){    if(root == NULL)        return HeadandTail(NULL,NULL);    BSTreeNode *headPtr = root;    BSTreeNode *endPtr = root;    if(root->m_pLeft != NULL)    {        HeadandTail lResult = BSTreeToDlist(root->m_pLeft);        headPtr = lResult.first;        lResult.second->m_pRight = root;        root->m_pLeft = lResult.second;    }    if(root->m_pRight != NULL)    {        HeadandTail rResult = BSTreeToDlist(root->m_pRight);        endPtr = rResult.second;        rResult.first->m_pLeft = root;        root->m_pRight = rResult.first;    }    return HeadandTail(headPtr, endPtr);}int main(){    /* 测试树            10                         /\                        /  \                       6   14    */    BSTreeNode *root = new BSTreeNode;    root->m_nValue = 10;    BSTreeNode *left = new BSTreeNode;    left->m_nValue = 6;    left->m_pLeft = NULL;    left->m_pRight = NULL;    BSTreeNode *right = new BSTreeNode;    right->m_nValue = 14;    right->m_pLeft = NULL;    right->m_pRight = NULL;    root->m_pLeft = left;    root->m_pRight = right;    HeadandTail result = BSTreeToDlist(root);    BSTreeNode *head = result.first;    BSTreeNode *tail = result.second;    while(head != NULL)    {        cout<<head->m_nValue<<" ";        head = head->m_pRight;    }    cout<<endl;    while(tail != NULL)    {        cout<<tail->m_nValue<<" ";        tail = tail->m_pLeft;    }    cout<<endl;    return 0;}


非递归方法

该问题的实质是中序遍历二元树,将当前遍历的节点和前一次遍历的节点连接起来即可。

源码待补充


0 0
原创粉丝点击