二叉树的递归创建和遍历
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;}
相关文章推荐
- 二叉树的创建与遍历(递归创建与遍历)
- 二叉树创建及遍历算法(递归及非递归)
- 二叉树的创建即遍历(递归方式)
- 九度OJ 1184 二叉树递归创建遍历
- 二叉树——创建,递归遍历输出
- ::递归实现——创建二叉树 ----> 装入数据--->遍历---> 显示 --->销毁
- 数据结构复习:链式二叉树创建和递归遍历
- 二叉树 前序遍历的非递归实现 中序遍历的非递归实现 后序遍历的非递归实现 创建二叉树
- java实现二叉树的创建及三种递归遍历
- 采用二叉链表结构实现二叉树,并以递归遍历思想实现二叉树的创建、二叉树的遍历(先序、中序、后序和层次遍历)
- 二叉树(2)二叉树创建的3种方法,二叉树的递归遍历,二叉树的销毁
- 模板二叉树的创建与深度遍历(栈、递归)和广度优先遍历(队列)
- 二叉树创建、删除、(递归/非递归)先序(中序/后序)遍历
- 九度OJ 1184 二叉树递归创建遍历
- 二叉树的创建与递归遍历
- 二叉树的创建、层次遍历、递归遍历、非递归遍历
- 二叉树的创建与先、中、后序遍历递归实现
- 二叉树的创建遍历 递归实现
- 二叉树的创建与遍历(递归版本)
- 二叉树创建及遍历算法(递归及非递归)[整理]