zoukankan      html  css  js  c++  java
  • 二叉树转双向链表

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

    先创建一个头结点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;
    }

                                                                      

  • 相关阅读:
    电商总结(二)日志与监控系统的解决方案
    倾力推荐,哪一本让你想要加入书单
    电商总结(一)小型电商网站的架构
    聊一聊如何提升团队开发效率
    Nancy总结(三)Nancy资料介绍
    【推荐】2016年不得不读的九本好书
    Solr学习总结(七)Solr搜索引擎的整体架构
    再见 2015,你好 2016
    Solr学习总结(六)SolrNet的高级用法(复杂查询,分页,高亮,Facet查询)
    Solr学习总结(五)SolrNet的基本用法及CURD
  • 原文地址:https://www.cnblogs.com/yihua/p/3348491.html
Copyright © 2011-2022 走看看