[원] 두 갈래 나무의 생성과 반복

2257 단어
package com.ccl.data.organization;

/**
 * @author Administrator
 * @since 2012/4/10
 */
class Node {

	public Node leftChild;
	public Node rightChild;

	public int data;

	public Node() {
	}

	public Node(int data, Node left, Node right) {
		this.data = data;
		this.leftChild = left;
		this.rightChild = right;
	}
}

 
package com.ccl.data.organization;

public class BinaryTree {

	public int[] array = new int[] { 109, 12, 32, -1, -1, -1, 3, 543, -1, -1,
			29, -1, -1 };

	public int index = 0;

	/**
	 *  
	 * 
	 * @since 2012/4/10 20:56
	 * @param node
	 * @return root <b> , </b>
	 */
	public Node init(Node node) {

		if (array[index] == -1) {

			node = null;
			index++;// ++

		} else {

			node.leftChild = new Node();//  
			node.rightChild = new Node();//

			node.data = array[index];
			index++; // ++
			node.leftChild = init(node.leftChild);

			node.rightChild = init(node.rightChild);

		}

		return node;

	}

	/**
	 *  
	 * 
	 * @param node
	 */
	public void preorderTree(Node node) {

		if (node != null) {

			System.out.print("" + node.data + "\t");
			preorderTree(node.leftChild);
			preorderTree(node.rightChild);
		}

	}

	/**
	 *  
	 * 
	 * @param node
	 */
	public void inorder(Node node) {

		if (node == null)
			return;
		else {
			inorder(node.leftChild);
			System.out.print(node.data + "\t");
			inorder(node.rightChild);
		}

	}

	/**
	 *  
	 * 
	 * @param node
	 */
	public void postorder(Node node) {
		if (node == null)
			return;
		else {
			postorder(node.leftChild);
			postorder(node.rightChild);
			System.out.print(node.data + "\t");
		}
	}

	@Override
	public String toString() {

		return super.toString();
	}
}

 
package com.ccl.data.organization;

public class DataOrganizationDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		BinaryTree tree = new BinaryTree();

		Node root = new Node();

		tree.init(root);

		tree.preorderTree(root);
		System.out.println();

		tree.inorder(root);
		System.out.println();

		tree.postorder(root);
		System.out.println();
	}

}

 
저자: chengchanglun 2012-4-10 21:20:02 원문 링크 발표
읽기: 106 설명: 0 설명 보기

좋은 웹페이지 즐겨찾기