• 数据结构-二叉搜索树与双向链表


    题目:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。

    分析:首先不能创建新的结构,只能在树的前提下进行改变指针的指向。又由于是二叉搜索树,可以通过画图分析可知,二叉搜索树的左子树小于根节点小于右子树,可以发现是个递归过程也是一个中序遍历。所以只需要在中序那块进行指针调整。

    /*
    剑指offer面试题27
    */
    #include <iostream>
    
    using namespace std;
    
    struct BinaryTree{
        int data;
        BinaryTree* lchild;
        BinaryTree* rchild;
    };
    
    void Convert(BinaryTree* root,BinaryTree** pList){
    
        if(root == NULL){
            return;
        }
    
        BinaryTree* pTree = root;
    
        if(pTree->lchild){
            Convert(pTree->lchild,pList);
        }
    
        // 双链表
        pTree->lchild = *pList;
        if(*pList != NULL){
            (*pList)->rchild = pTree;
        }
        *pList = pTree;
    
        if(pTree->rchild){
            Convert(pTree->rchild,pList);
        }
    
    }
    
    BinaryTree* Convert(BinaryTree* root){
        BinaryTree* pList = NULL;
        Convert(root,&pList);
    
        BinaryTree* pListHead = pList;
    
        while(pListHead->lchild != NULL){
            pListHead = pListHead->lchild;
        }
        return pListHead;
    }
    
    BinaryTree* Create(){
        BinaryTree* root = new BinaryTree;
        root->data = 10;
        BinaryTree* lchild = new BinaryTree;
        lchild->data = 6;
        BinaryTree* rchild = new BinaryTree;
        rchild->data = 14;
        root->lchild = lchild;
        root->rchild = rchild;
    
        BinaryTree* lchild1 = new BinaryTree;
        lchild1->data = 4;
        BinaryTree* rchild1 = new BinaryTree;
        rchild1->data = 8;
        lchild->lchild = lchild1;
        lchild->rchild = rchild1;
    
        BinaryTree* lchild2 = new BinaryTree;
        lchild2->data = 12;
        BinaryTree* rchild2 = new BinaryTree;
        rchild2->data = 16;
        rchild->lchild = lchild2;
        rchild->rchild = rchild2;
    
        lchild1->lchild = NULL;
        lchild1->rchild = NULL;
        rchild1->lchild = NULL;
        rchild1->rchild = NULL;
    
        lchild2->lchild = NULL;
        lchild2->rchild = NULL;
        rchild2->lchild = NULL;
        rchild2->rchild = NULL;
    
        return root;
    }
    
    int main(){
        BinaryTree* root = Create();
        BinaryTree* pList = Convert(root);
    
        while(pList->rchild != NULL){
            cout << pList->data << " ";
            pList = pList->rchild;
        }
        cout << endl;
        while(pList->lchild != NULL){
            cout << pList->data << " ";
            pList = pList->lchild;
        }
    
        return 0;
    }
  • 相关阅读:
    网络-路由交换-IPv4-Cisco-协议概要
    网络-路由交换-IPv4-Cisco-协议基础
    网络-路由交换-网络安全-华为-ACL分类
    泰克-OSPF
    网络-路由交换-网络安全-华为-DHCP基础
    不同系统下的数据参考
    model一定是和数据库表对应的么?
    NUnit属性-百度Nunit-Gui
    NUnit属性
    NUnit详细使用方法
  • 原文地址:https://www.cnblogs.com/wn19910213/p/3747719.html
Copyright © 2020-2023  润新知