您的位置:首页 > 其它

二叉树的递归创建和遍历

2012-09-01 23:26 267 查看
/*
author:justinzhang
email:uestczhangchao@gmail.com
time:2012-8-2015:52:27
des.:usingnonrecursivemethodtotraversebinarytree
*/
#include<iostream>
usingnamespacestd;
template<typenameT>classbtree
{
public:
Tdata;
btree*lchild,*rchild;
};
/*createbinarytree,withoneparameter.
thebinarytreeisinputedthroughpreorder,
1
23,isinputas12-1-13-1-1,(-1representnilnode);
*/
btree<double>*create_btr(btree<double>**root)
{
doubledata;
cin>>data;
/*-1.0representthenilnode*/
if(data==-1.0)
{
*root=NULL;
}
else
{
*root=newbtree<double>();
(*root)->data=data;
(*root)->lchild=create_btr(&(*root)->lchild);
(*root)->rchild=create_btr(&(*root)->rchild);
}
return*root;
}
/*createbinarytreewithoutparameter!*/
btree<double>*create_btr()
{
doubledata;
cin>>data;
if(data==-1)
returnNULL;//returnnillnode
else
{
btree<double>*T=newbtree<double>;
T->data=data;
T->lchild=create_btr();
T->rchild=create_btr();
returnT;
}
}
voidpreorder(btree<double>*r)
{
if(r==NULL)
return;
cout<<r->data<<endl;
preorder(r->lchild);
preorder(r->rchild);
}
voidinorder(btree<double>*r)
{
if(NULL==r)
return;
inorder(r->lchild);
cout<<r->data<<endl;
inorder(r->rchild);
}
voidpostorder(btree<double>*r)
{
if(NULL==r)
return;
postorder(r->lchild);
postorder(r->rchild);
cout<<r->data<<endl;
}
intmain()
{
btree<double>*root=NULL;
create_btr(&root);
//btree<double>*T=create_btr();
preorder(root);
inorder(root);
postorder(root);
//inorder(T);
return0;
}

.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: