• 二叉树转双向链表


    这是一道挺有趣的题,其解题的思路主要还是二叉树的中序遍历

    先创建一个头结点List,然后通过中序遍历二叉树,把结点串起来即可!

    注意点:

    1、需要有一个指针来指向上一个已遍历过的结点

    2、如果不创建头结点,在后面遍历判断时比较麻烦

    #include<iostream>
    using namespace std;
    
    struct Node{
        int val;
        Node *lchild;
        Node *rchild;
    };
    
    //创建二叉树
    Node *CreateTree(){
        char lflag='n',rflag='n';
        Node*root=new Node;
        root->lchild=NULL;
        root->rchild=NULL;
    
        cout<<"请输入结点的值:"<<endl;
        cin>>root->val;
        
        cout<<"该结点是否有左子树?请输入Y or N:";
        cin>>lflag;
        if(lflag=='y'||lflag=='Y')root->lchild=CreateTree();
        else root->lchild =NULL;
    
        cout<<"该结点是否有右子树?请输入Y or N:";
        cin>>rflag;
        if(rflag=='y'||rflag=='Y')root->rchild=CreateTree();
        else root->rchild =NULL;
    
        return root;
    }
    
    //先序遍历二叉树
    void ShowTreeXian(Node*root)
    {
        if(root!=NULL)cout<<root->val<<" ";
        if(root->lchild !=NULL)ShowTreeXian(root->lchild );
        if(root->rchild !=NULL)ShowTreeXian(root->rchild );
    }
    
    //p,为上一个已遍历过的结点,初始化为空头结点,二叉树转双向链表
    void TreeToList(Node *root,Node *&p){
        if(root->lchild !=NULL)TreeToList(root->lchild,p);
        root->lchild =p;
        p->rchild =root;
        p=root;
        if(root->rchild !=NULL)TreeToList(root->rchild,p);
    }
    
    //双向链表的遍历
    void ShowList(Node *root)
    {
        cout<<"从左到右:"<<endl;
        while(root->rchild !=NULL){        
            cout<<root->rchild ->val<<" ";
            root=root->rchild ;
        }
        
        cout<<"从右到左:"<<endl;
        while(root->lchild!=NULL){
            cout<<root->val<<" ";
            root=root->lchild ;
        }
    }
    
    int main(){
    
        cout<<"创建二叉树:"<<endl;
        Node*root=CreateTree();
    
        cout<<"先序遍历二叉树:"<<endl;
        ShowTreeXian(root);
    
        cout<<"二叉树转双向链表"<<endl;
        Node *List=new Node;
        List->lchild=NULL;
        List->rchild =NULL;
        List->val =0;
        Node *p=List;
        TreeToList(root,p);           
    
        cout<<"双向链表的遍历"<<endl;
        ShowList(List);
    
        system("pause");
    
        return 0;
    }

                                                                      

  • 相关阅读:
    MyBaits基本要素
    自定义MVC
    mybatis之多个对象自动装配问题
    idea之映射servlet问题
    idea工程jdk设置问题
    初识多线程之基础知识与常用方法
    多线程之模拟数据库连接
    mybatis配置文件详解
    初识mybatis之入门案例
    mybatis中打印sql语句
  • 原文地址:https://www.cnblogs.com/yihua/p/3348491.html
Copyright © 2020-2023  润新知