码迷,mamicode.com
首页 > 编程语言 > 详细

java二叉树的实现和遍历

时间:2016-07-10 12:34:56      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * Java实现二叉树
 */
public class BinaryTree {

	int treeNode;
	BinaryTree leftTree;
	BinaryTree rightTree;
	
	public BinaryTree(int Data) {
		// TODO Auto-generated constructor stub
		treeNode=Data;
		leftTree=null;
		rightTree=null;
	}
	
	public void insert(BinaryTree node,int data) {
		if(data >node.treeNode){
			if(node.rightTree==null){
				rightTree=new BinaryTree(data);
			}else{
				this.insert(node.rightTree, data);
			}
		}else{
			if (node.leftTree==null) {
				leftTree=new BinaryTree(data);
			}else{
				this.insert(node.leftTree, data);
			}
		}
	}
}

 

/*
 * 对定义二叉树的,先序遍历,中序遍历,后序遍历
 */
public class BinaryTreeOrder {

	public static void preOrder(BinaryTree root) { // 先序遍历
		if (root != null) {
			System.out.print(root.treeNode + "-");
			preOrder(root.leftTree);
			preOrder(root.rightTree);
		}
	}

	public static void inOrder(BinaryTree root) { // 中序遍历

		if (root != null) {
			inOrder(root.leftTree);
			System.out.print(root.treeNode + "--");
			inOrder(root.rightTree);
		}
	}

	public static void postOrder(BinaryTree root) { // 后序遍历

		if (root != null) {
			postOrder(root.leftTree);
			postOrder(root.rightTree);
			System.out.print(root.treeNode + "---");
		}
	}

	public static void main(String[] args) {
		int[] array = { 12, 76, 35, 22, 16, 48, 90, 46, 9, 40 };
		BinaryTree root = new BinaryTree(array[0]); // 创建二叉树
		for (int i = 1; i < array.length; i++) {
			root.insert(root, array[i]); // 向二叉树中插入数据
		}
		System.out.println("先序遍历:");
		preOrder(root);
		System.out.println();
		System.out.println("中序遍历:");
		inOrder(root);
		System.out.println();
		System.out.println("后序遍历:");
		postOrder(root);
	}
}

 

java二叉树的实现和遍历

标签:

原文地址:http://www.cnblogs.com/yoyohong/p/5657314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!