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 查看评论