算法篇----二叉树遍历

本次的算法主要描述二叉树的遍历:

using System;
using System.Collections.Generic;
namespace NET.MST.Thirteenth.BinaryTree
{
class MainClass
{
/// <summary>
/// 测试二叉树,和其中序、后序遍历
/// </summary>
static void Main(string[] args)
{
int[] data = new int[] { 6, 1, 3, 9, 2, 7, 11 };
BinaryTree root
= BinaryTree.GenerateBinaryTree(data);
Console.Write(
"中序遍历:");
root.InOrder();
Console.Write(
"\r\n");
Console.Write(
"后序遍历:");
root.LastOrder();
Console.Write(
"\r\n");
Console.Read();
}
}
/// <summary>
/// 二叉树的实现
/// </summary>
partial class BinaryTree
{
//左子树指针
private BinaryTree _left = null;
//右子树指针
private BinaryTree _right = null;
//节点的值,这里以整数表示
private int _value;
/// <summary>
/// 构造方法,左右子树设为null
/// </summary>
/// <param name="val">节点值</param>
public BinaryTree(int val)
{
_value
= val;
}
/// <summary>
/// 构造方法
/// </summary>
/// <param name="val">节点值</param>
/// <param name="left">左子树指针</param>
/// <param name="right">右子树指针</param>
public BinaryTree(int val, BinaryTree left, BinaryTree right)
{
_value
= val;
_left
= left;
_right
= right;
}
//读写属性
public BinaryTree Left
{
get
{
return _left;
}
set
{
_left
= value;
}
}
public BinaryTree Right
{
get
{
return _right;
}
set
{
_right
= value;
}
}
public int Value
{
get
{
return _value;
}
set
{
_value
= value;
}
}
}
/// <summary>
/// 二叉树的生成和插入
/// </summary>
partial class BinaryTree
{
/// <summary>
/// 静态方法用以从一个数组生成一颗二叉树
/// 这里采用的是有序的插入
/// </summary>
/// <param name="data">输入数组</param>
/// <returns>返回根节点</returns>
public static BinaryTree GenerateBinaryTree(int[] data)
{
//确保数组非空
if (data.Length <= 0)
return null;
//生成根节点
BinaryTree root = new BinaryTree(data[0]);
//确保需要生成左子树或者右子树
if (data.Length <= 1)
return root;
//逐一插入整个数组
for (int i = 1; i < data.Length; i++)
root.InsertElement(data[i]);
return root;
}
/// <summary>
/// 有序地插入元素,插入的结果是中序遍历该二叉树可以获得一个有序序列
/// </summary>
/// <param name="val">需要插入的值</param>
public void InsertElement(int val)
{
//需要插在左子树中
if (val <= _value)
{
//左子树为空,插入新元素
if (_left == null)
{
BinaryTree node
= new BinaryTree(val);
_left
= node;
}
//左子树非空,递归
else
_left.InsertElement(val);
}
//需要插在右子树中
else
{
//右子树为空,插入新元素
if (_right == null)
{
BinaryTree node
= new BinaryTree(val);
_right
= node;
}
//右子树非空,递归
else
_right.InsertElement(val);
}
}
}
/// <summary>
/// 遍历二叉树
/// </summary>
partial class BinaryTree
{
/// <summary>
/// 中序遍历二叉树
/// </summary>
public void InOrder()
{
//使用递归算法
if (_left != null)
_left.InOrder();
Console.Write(
"{0},", _value);
if (_right != null)
_right.InOrder();
}
/// <summary>
/// 后序遍历二叉树
/// </summary>
public void LastOrder()
{
//使用递归算法
if (_left != null)
_left.LastOrder();
if (_right != null)
_right.LastOrder();
Console.Write(
"{0},", _value);
}
}
}

posted @ 2011-05-20 20:34  brainmao  阅读(415)  评论(0编辑  收藏  举报