标签:
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