zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Androidstudio 使用git插件提交代码
    androidstudio上传代码到git上
    tcpdump的简单使用
    使用nmap工具查询局域网某个网段正在使用的ip地址
    网段的划分
    jenkins配置源码管理git
    shell条件测试test
    shell简单用法笔记(shell中数值运算)二
    shell简单用法笔记(一)
    如何解决audiodg占用内存高(停止与重启audiodg服务)
  • 原文地址:https://www.cnblogs.com/wangchy0927/p/2496032.html
Copyright © 2011-2022 走看看