将二叉树转换为双向链表:
5
/ \
2 7
/ \ / \
1 3 6 8
双向链表:1=2=3=5=6=7=8
#include<stdafx.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<stack>
#include<iostream>
using namespace std;
struct BSTree
{
int mvalue;
BSTree *leftTree;
BSTree *rightTree;
};
BSTree* doublelist=NULL;
BSTree* pheadlist=NULL;
//树的创建
void createTree(BSTree* &root,int value)
{
if(root==NULL)
{
root=(BSTree*)malloc(sizeof(BSTree));
root->mvalue=value;
root->leftTree=NULL;
root->rightTree=NULL;
return;
}
else
if(root->mvalue>value)
createTree(root->leftTree,value);
else
createTree(root->rightTree,value);
}
//按层次遍历树
void Nodeprint(BSTree * root)
{
if(root==NULL)
return;
stack<BSTree*> p;
BSTree* tree;
p.push(root);
while(p.size()>0)
{
tree=p.top();
cout<<tree->mvalue<<" ";
p.pop();
if(tree->rightTree!=NULL)
p.push(tree->rightTree);
if(tree->leftTree!=NULL)
p.push(tree->leftTree);
}
cout<<endl;
}
//将树转换为双向链表
void convertToList(BSTree* pcurrent)
{
pcurrent->leftTree=doublelist;
if(doublelist!=NULL)
doublelist->rightTree=pcurrent;
else
pheadlist=pcurrent;
doublelist=pcurrent;
}
void eroToList(BSTree* root)
{
if(root==NULL)
return;
if(root->leftTree!=NULL)
eroToList(root->leftTree);
convertToList(root);
if(root->rightTree!=NULL)
eroToList(root->rightTree);
}
int main(int argc,char**argv)
{
int a[]={5,2,3,1,7,8,6};
BSTree* root=NULL;
int len=sizeof(a)/sizeof(int);
for(int i=0;i<len;i++)
createTree(root,a[i]);
Nodeprint(root);
eroToList( root);
cout<<endl;
while(pheadlist!=NULL)
{
cout<<pheadlist->mvalue<<" ";
pheadlist=pheadlist->rightTree;
}
cout<<endl;
return 0;
}