二叉树转双向链表

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

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

 

                                                                  

posted @ 2013-10-01 14:54  宁静致远--Ada  阅读(685)  评论(0编辑  收藏  举报