(算法)二叉树转换为双向链表

 

 将二叉树转换为双向链表:

        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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值