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

二叉排序树,二叉树的中序,先序,后序遍历

时间:2015-08-07 14:45:33      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

public class BinaryTree {
	public static void main(String[] args) {
		int[] data = new int[10];
		for(int i = 0; i < data.length; i++) {
			data[i] = (int)(Math.random() * 100) + 1;
			System.out.print(data[i] + " ");
		}
		System.out.println();
		Node root = new Node();
		root.value = data[0];
		for(int i = 1; i < data.length; i++) {
			root.store(data[i]);
		}
		
		root.find(data[7]);
		System.out.println();
		System.out.println("----------------");
		root.find(23);
		System.out.println();
		System.out.println("----------------");
		root.preSearch();
		System.out.println();
		System.out.println("----------------");
		root.midSearch();
		System.out.println();
		System.out.println("----------------");
		root.afterSearch();
		System.out.println();
		System.out.println("----------------");
	}
}


class Node {
	int value;
	Node left;
	Node right;
	
	public void store(int value) {
		if(value < this.value) {
			if(left == null) {
				left = new Node();
				left.value = value;
			} else {
				left.store(value);
			}
		} else {
			if(right == null) {
				right = new Node();
				right.value = value;
			} else {
				right.store(value);
			}
		}
	}
	
	public boolean find(int value) {
		System.out.println("find : " + this.value);
		if(value == this.value) {
			return true;
		} else if(value < this.value) {
			if(left == null) {
				return false;
			} else {
				return left.find(value);
			} 
		} else {
			if(right == null) {
				return false;
			} else {
				return right.find(value);
			}
		}
	}
	
	public void preSearch() {
		System.out.print(value + " ");
		if(left != null) {
			left.preSearch();
		}
		if(right != null) {
			right.preSearch();
		}
	}
	public void midSearch() {
		
		if(left != null) {
			left.midSearch();
		}
		System.out.print(value + " ");
		if(right != null) {
			right.midSearch();
		}
	}
	public void afterSearch() {
		
		if(left != null) {
			left.afterSearch();
		}
		if(right != null) {
			right.afterSearch();
		}
		System.out.print(value + " ");
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

二叉排序树,二叉树的中序,先序,后序遍历

标签:

原文地址:http://blog.csdn.net/qhairen/article/details/47338875

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