二叉树之实现排序二叉树

package me.wcy.j2se.datastructure;

/**
 * 排序二叉树
 * 
 * @author chenyan.wang
 *
 */
public class BinaryTree {

	public static void main(String[] args) {
		BinaryTree biTree = new BinaryTree();
		int[] data = { 2, 8, 7, 4, 9, 3, 1, 6, 7, 5 };
		biTree.buildTree(data);
		System.out.print("中序遍历:");
		biTree.inOrder();
		System.out.println();
		System.out.print("先序遍历:");
		biTree.preOrder();
		System.out.println();
		System.out.print("后序遍历:");
		biTree.postOrder();
		System.out.println();
	}

	private TreeNode root;

	public BinaryTree() {
	}

	/**
	 * 将data插入到排序二叉树中
	 * 
	 * @param data
	 */
	public void insert(int data) {
		TreeNode node = new TreeNode(data);
		if (root == null) {
			root = node;
		} else {
			TreeNode current = root;
			TreeNode parent;
			while (true) {// 寻找插入位置
				parent = current;
				if (data < parent.data) {
					current = parent.left;
					if (current == null) {
						parent.left = node;
						return;
					}
				} else {
					current = parent.right;
					if (current == null) {
						parent.right = node;
						return;
					}
				}
			}
		}
	}

	/**
	 * 将数值输入构建二叉树
	 * 
	 * @param data
	 */
	public void buildTree(int[] data) {
		for (int n : data) {
			insert(n);
		}
	}

	/**
	 * 中序遍历
	 */
	public void inOrder() {
		inOrder(root);
	}

	public void inOrder(TreeNode localRoot) {
		if (localRoot != null) {
			inOrder(localRoot.left);
			System.out.print(localRoot.data + " ");
			inOrder(localRoot.right);
		}
	}

	/**
	 * 先序遍历
	 */
	public void preOrder() {
		preOrder(root);
	}

	public void preOrder(TreeNode localRoot) {
		if (localRoot != null) {
			System.out.print(localRoot.data + " ");
			preOrder(localRoot.left);
			preOrder(localRoot.right);
		}
	}

	/**
	 * 后序遍历
	 */
	public void postOrder() {
		postOrder(root);
	}

	public void postOrder(TreeNode localRoot) {
		if (localRoot != null) {
			postOrder(localRoot.left);
			postOrder(localRoot.right);
			System.out.print(localRoot.data + " ");
		}
	}

}

输出结果:

中序遍历:1 2 3 4 5 6 7 7 8 9 

先序遍历:2 1 8 7 4 3 6 5 7 9 

后序遍历:1 3 5 6 4 7 7 9 8 2 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值