会员
周边
众包
新闻
博问
闪存
赞助商
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
Just do it...
学而不思则罔,思而不学则殆...
博客园
首页
新随笔
联系
管理
订阅
二叉树遍历:先序、中序、后序和层次遍历
public
class
BinaryNode
{
public
int
Data;
public
BinaryNode Left;
public
BinaryNode Right;
}
public
class
BinaryTree
{
public
void
PreOrder(BinaryNode node)
{
if
(node
!=
null
)
{
Console.WriteLine(node.Data);
PreOrder(node.Left);
PreOrder(node.Right);
}
}
public
void
MidOrder(BinaryNode node)
{
if
(node
!=
null
)
{
MidOrder(node.Left);
Console.WriteLine(node.Data);
MidOrder(node.Right);
}
}
public
void
AfterOrder(BinaryNode node)
{
if
(node
!=
null
)
{
AfterOrder(node.Left);
AfterOrder(node.Right);
Console.WriteLine(node.Data);
}
}
public
void
LayerOrder(BinaryNode node)
{
if
(node
!=
null
)
{
CurrentLayer(node.Left);
CurrentLayer(node.Right);
LayerOrder(node.Left);
LayerOrder(node.Right);
}
}
private
void
CurrentLayer(BinaryNode node)
{
if
(node
!=
null
)
{
Console.WriteLine(node.Data);
}
}
}
测试:
BinaryNode n1
=
new
BinaryNode();
n1.Data
=
27
;
BinaryNode n2
=
new
BinaryNode();
n2.Data
=
83
;
BinaryNode n3
=
new
BinaryNode();
n3.Data
=
123
;
BinaryNode n4
=
new
BinaryNode();
n4.Data
=
98
;
BinaryNode n5
=
new
BinaryNode();
n5.Data
=
94
;
BinaryNode n6
=
new
BinaryNode();
n6.Data
=
48
;
BinaryNode n7
=
new
BinaryNode();
n7.Data
=
61
;
n1.Left
=
n2;
n1.Right
=
n3;
n1.Left.Left
=
n4;
n1.Left.Right
=
n5;
n1.Right.Right
=
n6;
n1.Right.Right.Left
=
n7;
BinaryTree bTree
=
new
BinaryTree();
Console.WriteLine(
"
Pre Order Binary Tree:
"
);
bTree.PreOrder(n1);
Console.WriteLine(
"
Midd Order Binary Tree:
"
);
bTree.MidOrder(n1);
Console.WriteLine(
"
After Order Binary Tree:
"
);
bTree.AfterOrder(n1);
Console.WriteLine(
"
Layer Order Binary Tree:
"
);
bTree.LayerOrder(n1);
Console.ReadLine();
posted @
2008-03-05 14:09
Ready!
阅读(
496
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告