Java 구현 두 갈래 트리 구축 및 세 가지 반복

8735 단어 Java 학습

Java 구현 두 갈래 트리 구축 및 세 가지 반복

public class BinTree {
	static int[] array = {1,2,3,4,5,6,7,8,9};
	static List nodelist = null;
	
	/* */
	public static class Node {
		Node leftChirld;
		Node rightChirld;
		int data;
		public Node(int data) {
			leftChirld=null;
			rightChirld=null;
			this.data=data;
		}
	}
	
	/* */
	public static void build() {
		nodelist=new LinkedList();
		
		for(int node=0;nodenew Node(array[node]));
		}
		
		for(int index=0;index2-1;index++) {
			nodelist.get(index).leftChirld = nodelist.get(index*2+1);
			nodelist.get(index).rightChirld = nodelist.get(index*2+2);
			
		}
		
		int last = array.length/2-1;
		nodelist.get(last).leftChirld = nodelist.get(last*2+1);
		
		/* , */
		if (array.length%2==1) {
			nodelist.get(last).rightChirld = nodelist.get(last*2+2);
		}

	}
	
	/* */
	public static void proOrder(Node node) {
		if (node==null) {
			return;
		}
		
		System.out.println(node.data+"");
		proOrder(node.leftChirld);
		proOrder(node.rightChirld);
	}
	
	
	/* */
	public static void inOrder(Node node) {
		if (node==null) {
			return;
		}
		inOrder(node.leftChirld);
		System.out.println(node.data+"");
		inOrder(node.rightChirld);
	}
	
	/* */
	public static void postOrder(Node node) {
		if (node==null) {
			return;
		}
		
		postOrder(node.leftChirld);
		postOrder(node.rightChirld);
		System.out.println(node.data+"");
		
	}
	
	
	

	public static void main(String[] args) {
		BinTree binTree = new BinTree();
		binTree.build();
		
		/* */
		Node root = nodelist.get(0);
		
		System.out.println(" :");  
		binTree.proOrder(root);
		System.out.println("");
		
		System.out.println(" :");  
		binTree.inOrder(root);
		System.out.println("");
		
		
		System.out.println(" :");  
		binTree.postOrder(root);
		
	}

}

좋은 웹페이지 즐겨찾기