java实现二叉树

View Code
 1 package com.test.suanfa;
 2 
 3 public class BinaryTreeTest{
 4     public static void main(String args[]){
 5         
 6         BinaryTreeTest b = new BinaryTreeTest();
 7         int data[] = { 12, 11, 34, 45, 67, 89, 56, 43, 22, 98 };
 8         BinaryTree root = new BinaryTree(data[0]);
 9         System.out.print("二叉树的中的数据:  ");
10         for (int i = 1; i < data.length; i++){
11             root.insertTree(root, data[i]);
12             System.out.print(data[i - 1] + ";");
13         }
14         System.out.println(data[data.length - 1]);
15         int key = 36;
16         if (b.searchkey(root, key))
17             System.out.println("找到了:" + key);
18         else
19             System.out.println("没有找到:" + key);
20     }
21 
22     public boolean searchkey(BinaryTree root, int key){
23 
24         boolean bl = false;
25         if (root == null){
26             bl = false;
27             return bl;
28         }
29         else if (root.data == key){
30             bl = true;
31             return bl;
32         }
33         else if (key >= root.data){
34             return searchkey(root.rightpoiter, key);
35         }
36         return searchkey(root.leftpoiter, key);
37     }
38 }
39 
40 class BinaryTree{
41 
42     int data;
43     BinaryTree leftpoiter;
44     BinaryTree rightpoiter;
45     BinaryTree(int data){
46 
47         this.data = data;
48         leftpoiter = null;
49         rightpoiter = null;
50     }
51 
52     public void insertTree(BinaryTree root, int data){
53 
54         if (data >= root.data){
55 
56             if (root.rightpoiter == null)
57                 root.rightpoiter = new BinaryTree(data);
58             else
59                 insertTree(root.rightpoiter, data);
60         }
61         else
62         {
63             if (root.leftpoiter == null)
64                 root.leftpoiter = new BinaryTree(data);
65             else
66                 insertTree(root.leftpoiter, data);
67         }
68     }
69 }

 

posted @ 2012-05-11 14:28  爱我所艾  阅读(239)  评论(0编辑  收藏  举报