java学习笔记(8)-树(1)
标签(空格分隔): 学习笔记
public class TreeCreate {
public class Node{
Object data;
Node leftNode;
Node rightNode;
public Node(Object data, Node leftNode, Node rightNode) {
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
}
//构造树-手动构造(菜没办法 )
Node n0=new Node(0, null, null);
Node n5=new Node(5, null, null);
Node n6=new Node(6, n5, null);
Node n3=new Node(3, null, null);
Node n2=new Node(2, null, n3);
Node n1=new Node(1, n0, n2);
Node n4=new Node(4, n1, n6);
public Node root=n4;
//前序遍历,输出为:4 1 0 2 3 6 5
public void previousSort(Node nodetmp) {
if(nodetmp!=null) {
System.out.print(nodetmp.data+" ");
previousSort(nodetmp.leftNode);
previousSort(nodetmp.rightNode);
}
}
//中序遍历,输出为:0 1 2 3 4 5 6
public void middleSort(Node nodetmp) {
if(nodetmp!=null) {
middleSort(nodetmp.leftNode);
System.out.print(nodetmp.data+" ");
middleSort(nodetmp.rightNode);
}
}
//后序遍历,输出为:0 3 2 1 5 6 4
public void behindSort(Node nodetmp) {
if(nodetmp!=null) {
behindSort(nodetmp.leftNode);
behindSort(nodetmp.rightNode);
System.out.print(nodetmp.data+" ");
}
}
public static void main(String[] args) {
TreeCreate t1=new TreeCreate();
t1.previousSort(t1.root);
System.out.println();
t1.middleSort(t1.root);
System.out.println();
t1.behindSort(t1.root);
}
}