分享

二叉排序数的实现

 昵称27015 2007-05-07
package net.oicp.shuangquan;
import java.io.*;
class Node{
 int data;
 Node lchild;
 Node rchild;
}
/*class Tree{
 
}*/
public class BinaryTree {
 /**
  * @param args
  */
 private Node root;
 public BinaryTree()
 {
  root=null;
 }
 public  void insert(int data)
 {
  Node tree=new Node();
  tree.data=data;
  //Node current=new Node();
  //current=tree;
  if(root==null)
  {
   root=tree;
   //current=root;
  }
  else
  {
   Node current,parent;
   current=root;
   while(true)
   {
    parent=current;
    if(data<current.data)
    {
     current=current.lchild;
     if(current==null)
     {
      parent.lchild=tree;
      return;
     }
     /*else
     {
      current=current.lchild;
     }*/
    }
    else
    {
     current=current.rchild;
     if(current==null)
     {
      parent.rchild=tree;
      return;
     }
    }
     
   }
   
  }
  
 }
 public Node find(int a)
 {
  Node current=root;
  while(a!=current.data)
  {
   current=a<current.data?current.lchild:current.rchild;
  }
  return current;
 }
 
 public static void main(String[] args) throws Exception
 {
  // TODO Auto-generated method stub
  BinaryTree tree=new BinaryTree();
  System.out.println("Please input the value: ");
  int j=Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
  while(j!=0)
  {
   tree.insert(j);
   j=Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
   
  }
  System.out.println("Please input the value what you want find: ");
  int i=Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine());
  System.out.println(tree.find(i).data);
  
 }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多