zoukankan
html css js c++ java
C#实现二叉树外带中序遍历(转载)
using
System;
namespace
BinaryTree
{
// Binary Tree的结点类
class
Node
{
public
int
Data {
get
;
set
; }
public
Node LeftSubNode {
get
;
set
; }
public
Node RightSubNode {
get
;
set
; }
// 结点为自己追加子结点(与向左/向右追加结点,形成递归)
public
void
Append(Node subNode)
{
if
(subNode.Data <=
this
.Data)
{
this
.AppendLeft(subNode);
}
else
{
this
.AppendRight(subNode);
}
}
// 向左追加
public
void
AppendLeft(Node subNode)
{
if
(
this
.LeftSubNode ==
null
)
{
this
.LeftSubNode = subNode;
}
else
{
this
.LeftSubNode.Append(subNode);
}
}
// 向右追加
public
void
AppendRight(Node subNode)
{
if
(
this
.RightSubNode ==
null
)
{
this
.RightSubNode = subNode;
}
else
{
this
.RightSubNode.Append(subNode);
}
}
// 结点显示自己的数据
public
void
ShowData()
{
Console.WriteLine(
"Data={0}"
,
this
.Data);
}
}
// BinaryTree类
class
Tree
{
// 根结点
public
Node Root {
get
;
set
; }
// 以根结点为起点,插入结点
public
void
Insert(Node newNode)
{
if
(
this
.Root ==
null
)
{
this
.Root = newNode;
}
else
{
this
.Root.Append(newNode);
}
}
// 重载,默认以根结点为起点遍历
public
void
MidTravel()
{
this
.MidTravel(
this
.Root);
}
// 中序遍历(递归)
public
void
MidTravel(Node node)
{
if
(node.LeftSubNode !=
null
)
{
this
.MidTravel(node.LeftSubNode);
}
node.ShowData();
if
(node.RightSubNode !=
null
)
{
this
.MidTravel(node.RightSubNode);
}
}
}
class
Program
{
static
void
Main(
string
[] args)
{
Tree tree =
new
Tree();
tree.Insert(
new
Node { Data = 3 });
tree.Insert(
new
Node { Data = 6 });
tree.Insert(
new
Node { Data = 2 });
tree.Insert(
new
Node { Data = 7 });
tree.Insert(
new
Node { Data = 18 });
tree.MidTravel();
}
}
}
查看全文
相关阅读:
Python 猜数小程序(练习)
Mysql 字符串日期互转
MaxCompute 语句笔记
数据仓库架构
Python 比较两个字符串的相似度
Python print
Python简单计算器
HashMap为什么线程不安全(死循环+数据丢失过程分析)
浅谈ArrayList、Vector和LinkedList
JAVA对象的浅克隆和深克隆
原文地址:https://www.cnblogs.com/guoxiaowen/p/1262571.html
最新文章
版本号的管理
缓存策略
Backbone事件机制核心源码(仅包含Events、Model模块)
跨源资源共享(CORS)
Facade模式实现文件上传(Flash+HTML5)
移除script标签引起的兼容性问题
命名冲突引发的现网故障
Java中static关键字用法总结
深入理解Java中的final关键字
bootstrap下,对数组循环处理的方法
热门文章
MySQL 中随机获取数据
MySQL用变量的方法添加伪序号列(自增序列)
MySQL中函数CONCAT及GROUP_CONCAT函数的使用
什么是Java序列化,如何实现java序列化
HashMap和HashTable的区别
short i=1;short i=i+1对或错,错的理由;short i+=1对或错,错的理由
HAVING COUNT(*) > 1的用法和理解
Mysql 调优笔记
Python 输出菱形
Python 读取目录,office文件分类
Copyright © 2011-2022 走看看