`

JAVA数据结构之二叉排序数

 
阅读更多

先定义树的节点类

package Tree;

/**
 * 树节点
 * @author Huangbin
 * d2014年7月18日
 */
public class Tree {

	Object obj;//内容
	Tree parent;//父节点
	Tree lchild;//左孩子节点
	Tree rchild;//右孩子节点

	public Tree(Object obj) {
		this.obj = obj;
	}

	public String toString() {
		return "" + obj;
	}
}

 

生成30个随机数,取第一个作为根节点,一次放入剩余29个数字。小的放左边大的放右边。使用中序遍历后就是排好序的了。

 

package Tree;

import java.util.Random;

/**
 * 二叉树
 * 
 * @author Huangbin
 * @data 2014年7月18日
 */
public class Main {

	public static void main(String[] args) {
		Main mu = new Main();
		int[] a = mu.creatArray();

		Tree root = new Tree(a[0]);// 取第一个元素建立树
		for (int i = 1; i < a.length; i++) {
			mu.put(a[i], null, root);//将第一个节点放进去,当作孩子节点,在put方法中会当作父节点。
		}
		mu.preOrderDisplay(root);
		System.out.println();
		mu.inOrderDisplay(root);// 中序遍历变成排序树
		System.out.println();
		mu.postOrderDisplay(root);
	}

	/**
	 * 创建30个数的数组
	 * 
	 * @return
	 */
	public int[] creatArray() {
		int arr[] = new int[30];
		Random rd = new Random();
		for (int i = 0; i < 30; i++) {
			arr[i] = rd.nextInt(100);
		}
		return arr;
	}

	/**
	 * 将元素放入树temp中生成二叉排序树
	 * 
	 * @param key
	 *            元素值
	 * @param root
	 *            临时保存父节点
	 * @param temp
	 *            将要放的位置(开始时候传入根节点)
	 */
	public void put(int key, Tree root, Tree temp) {
		if (temp == null) {// 找到了空位
			temp = new Tree(key);// 不存在就创建节点并结束方法
			if (key < (int) root.obj) {// 注意这个判断条件,在这个里面进行节点之间关系的链接
				root.lchild = temp;
			} else {
				root.rchild = temp;
			}
			temp.parent = root;
		} else {
			if (key < (int) temp.obj) {// 小于根节点放到左边去递归
				put(key, temp, temp.lchild);
			} else if (key > (int) temp.obj) {
				put(key, temp, temp.rchild);// 大于等于放右边去递归
			}
		}
	}

	/**
	 * 中序遍历
	 * 
	 * @param root
	 */
	public void inOrderDisplay(Tree root) {
		Tree tree = root;
		if (tree != null) {
			inOrderDisplay(tree.lchild);
			System.out.print(tree + " ");
			inOrderDisplay(tree.rchild);
		}
	}

	/**
	 * 先序遍历树root
	 * 
	 * @param root
	 */
	public void preOrderDisplay(Tree root) {
		Tree tree = root;
		if (tree != null) {
			System.out.print(tree + " ");
			preOrderDisplay(tree.lchild);
			preOrderDisplay(tree.rchild);
		}
	}

	/**
	 * 后续遍历树root
	 * 
	 * @param root
	 */
	public void postOrderDisplay(Tree root) {
		Tree tree = root;
		if (tree != null) {
			postOrderDisplay(tree.lchild);
			postOrderDisplay(tree.rchild);
			System.out.print(tree + " ");
		}
	}

}

运行结果:
88 49 23 15 38 27 26 28 32 48 42 54 50 67 65 62 57 58 66 80 75 76 82 86 85 
15 23 26 27 28 32 38 42 48 49 50 54 57 58 62 65 66 67 75 76 80 82 85 86 88 
15 26 32 28 27 42 48 38 23 50 58 57 62 66 65 76 75 85 86 82 80 67 54 49 88 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics