哈~ 今年刚学Java,感觉和C#有异曲同工之妙,呵呵,准备开始写博,记录自己学Java的点滴……
//接口
public interface BinTrees {
public void Firorder();
public void Secorder();
public void Inorder();
public void Insert(Node node);
}
//接口
public interface Nodeinter {
public void Append(Node node);
public void AppendLeft(Node node);
public void AppendRight(Node node);
}
class Node implements Nodeinter{
public int nodeNata;
public Node left;
public Node right;
public Node(int data)
{
this.nodeNata=data;
}
//追加结点
public void Append(Node node)
{
if(node.nodeNata <= this.nodeNata)
{
this.AppendLeft(node);
}
else
{
this.AppendRight(node);
}
}
//追加左子
public void AppendLeft(Node node)
{
if(this.left==null)
{
this.left=node;
}
else
{
this.left.Append(node);
}
}
//追加右子
public void AppendRight(Node node)
{
if(this.right==null)
{
this.right=node;
}
else
{
this.right.Append(node);
}
}
//打印结点
public void print()
{
if(this.nodeNata!='#')
{
System.out.println(this.nodeNata);
}
else
{
System.out.println('#');
}
}
}
public class BinTree implements BinTrees {
public Node root=null;
public BinTree(Node n)
{
this.root=n;
}
//添加结点
public void Insert(Node node)
{
if(this.root==null)
{
this.root=node;
}
else
{
this.root.Append(node);
}
}
public void Firorder()
{
this.FirOrder(root);
}
public void Secorder()
{
this.LasOrder(root);
}
public void Inorder()
{
this.InOrder(root);
}
//中序遍历递归算法
public void InOrder(Node node)
{
if(node!=null)
{
this.InOrder(node.left);
node.print();
this.InOrder(node.right);
}
}
//先序遍历递归算法
public void FirOrder(Node node)
{
if(node!=null)
{
node.print();
this.FirOrder(node.left);
this.FirOrder(node.right);
}
}
//后序遍历递归算法
public void LasOrder(Node node)
{
if(node!=null)
{
this.LasOrder(node.left);
this.LasOrder(node.right);
node.print();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Node n1=new Node(7);
Node n2=new Node(9);
Node n3=new Node(3);
Node n4=new Node(8);
Node n5=new Node(2);
Node n6=new Node(6);
BinTree bt=new BinTree(n1);
bt.Insert(n2);
bt.Insert(n3);
bt.Insert(n4);
bt.Insert(n5);
bt.Insert(n6);
bt.Inorder();
bt.Firorder();
bt.Secorder();
}
}