import java.util.Arrays;
import java.util.LinkedList;
public class MyTree {
public static Node createTree(LinkedList<Integer> list){
Node node = null;
if(list == null||list.isEmpty()){
return null;
}
Integer date = list.removeFirst();
if(date != null){
node = new Node(date);
node.leftchildren = createTree(list);
node.rightchildren = createTree(list);
}
return node;
}
private static class Node{
private Integer date;
private Node leftchildren;
private Node rightchildren;
public Node(Integer date){
this.date = date;
}
}
public static void preShowTree(Node node){
if(node == null){
return;
}
System.out.print(node.date+" ");
preShowTree(node.leftchildren);
preShowTree(node.rightchildren);
}
public static void inShowTree(Node node){
if(node == null){
return;
}
preShowTree(node.leftchildren);
System.out.print(node.date+" ");
preShowTree(node.rightchildren);
}
public static void endShowTree(Node node){
if(node == null){
return;
}
preShowTree(node.leftchildren);
preShowTree(node.rightchildren);
System.out.print(node.date+" ");
}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>(Arrays.asList(new Integer[]{1,2,5,null,8,null,7}));
Node treenode = createTree(list);
System.out.println("前序遍历\n");
preShowTree(treenode);
System.out.println("中序遍历\n");
inShowTree(treenode);
System.out.println("后序遍历\n");
endShowTree(treenode);
}
}
|