《剑指offer》面试题27——二叉搜索树与双向链表(C++)

二叉搜索树与双向链表

#include "bintree.h"

TreeNode* LastTail=NULL;      //记录已经转换部分的尾结点
TreeNode* RealHead=NULL;    //双向链表的头结点

void ConvertSub(TreeNode* Node)
{
        if(Node==NULL)
            return;

        if(Node->left != NULL)
        {
            ConvertSub(Node->left);   //左
        }                                                      //找到最左根节点

    if(LastTail==NULL)
    {
        LastTail=Node;
        RealHead= Node;   //双向链表的头结点
//        cout<<"双向链表为:   "<<endl;
//        cout<<LastTail->val<<"   ";
    }
    else
    {
        LastTail->right=Node;
        Node->left=LastTail;
        LastTail= Node;      //结点后移到新的位置,循环

    }

    if(Node->right!=NULL)
    {
         ConvertSub(Node->right);    //右;
    }
}

TreeNode* Convert(TreeNode* pRootOfTree)
{
        ConvertSub(pRootOfTree);
        return RealHead;
}

void PrintList(TreeNode *Node)
{
    TreeNode *tmp=Node;
    while(tmp!=NULL)
    {
        cout<<tmp->val<<"  ";
        tmp=tmp->right;
    }
}

int main()
{
        BinTree t;
        TreeNode* root=t.CreateTree();//创建二叉树

        cout<<"二叉树创建完毕..."<<endl;
        vector<int> myarray= PrintFromTopToBottom(root);
        Print1Dvec(myarray);

        cout<<endl;
       TreeNode* Head= Convert(root);
        cout<<"双向链表为:   "<<endl;
        PrintList(Head);

        return 0;
}



运行结果为:

二叉树创建完毕...
10  5  12  4  7  11  14

双向链表为:
4  5  7  10  11  12  14
Process returned 0 (0x0)   execution time : 0.295 s
Press any key to continue.

猜你喜欢

转载自blog.csdn.net/zhenaoxi1077/article/details/80438182