BNode类:
namespace btree.Tree {
public class BNode<T> {
public T data;
public BNode<T> left;
public BNode<T> right;
public BNode(T data, BNode<T> left=null, BNode<T> right=null) {
this.data = data;
this.left = left;
this.right = right;
}
}
}
BTree类
using System;
namespace btree.Tree {
public class BTree<T> {
public BNode<T> root;
public void preOrder() {
Console.Write("先根遍历二叉树:");
preOrder(this.root);
Console.WriteLine();
}
public void preOrder(BNode<T> p) {
if(p!=null) {
Console.Write(p.data);
preOrder(p.left);
preOrder(p.right);
}
}
public void inOrder() {
Console.Write("中根遍历二叉树:");
inOrder(this.root);
Console.WriteLine();
}
public void inOrder(BNode<T> p) {
if(p!=null) {
inOrder(p.left);
Console.Write(p.data);
inOrder(p.right);
}
}
public void postOrder() {
Console.Write("后根遍历二叉树:");
postOrder(this.root);
Console.WriteLine();
}
public void postOrder(BNode<T> p) {
if(p!=null) {
postOrder(p.left);
postOrder(p.right);
Console.Write(p.data);
}
}
}
}
测试程序:
using System;
using btree.Tree;
namespace btree
{
class Program
{
static void make(ref BTree<char> bTree) {
BNode<char> d_node = new BNode<char>('D',null,new BNode<char>('G'));
BNode<char> b_node = new BNode<char>('B',d_node,null);
BNode<char> f_node = new BNode<char>('F', new BNode<char>('H'), null);
BNode<char> c_node = new BNode<char>('C', new BNode<char>('E'), f_node);
BNode<char> a_node = new BNode<char>('A',b_node, c_node);
bTree.root = a_node;
}
static void Main(string[] args)
{
BTree<char> tree = new BTree<char>();
Program.make(ref tree);
tree.preOrder();
tree.inOrder();
tree.postOrder();
}
}
}
输出结果:
原树结构: