posts - 73,  comments - 55,  trackbacks - 0
// 建立二叉树并先根遍历的代码
public   class  BinaryTreeTest  {
 
public   static   void  main(String args[])  { // 主方法
  BinaryTreeTest b  =   new  BinaryTreeTest();
  
int  data[]  =   12 11 34 45 67 89 56 43 22 98  } ;
  BinaryTree root 
=   new  BinaryTree(data[ 0 ]);

  System.out.print(
" 二叉树的中的数据:   " );
// 建立二叉树
   for  ( int  i  =   1 ; i  <  data.length; i ++ {
   root.insertTree(root, data[i]);
   System.out.print(data[i 
-   1 +   " ; " );
  }


  System.out.println(data[data.length 
-   1 ]);

  
int  key  =  Integer.parseInt(args[ 0 ]);

  
if  (b.searchkey(root, key))  {
   System.out.println(
" 找到了: "   +  key);
  }
  else   {
   System.out.println(
" 没有找到: "   +  key);
  }

 }


 
public   boolean  searchkey(BinaryTree root,  int  key)  { // 查询
   boolean  bl  =   false ;
  
if  (root  ==   null {
   bl 
=   false ;
   
return  bl;
  }
  else   if  (root.data  ==  key)  {
   bl 
=   true ;
   
return  bl;
  }
  else   if  (key  >=  root.data)  {
   
return  searchkey(root.rightpoiter, key);
  }

  
return  searchkey(root.leftpoiter, key);
 }

}


class  BinaryTree  { // 二叉树类
  int  data;

 BinaryTree leftpoiter;

 BinaryTree rightpoiter;

 BinaryTree(
int  data)  {
  
this .data  =  data;
  leftpoiter 
=   null ;
  rightpoiter 
=   null ;
 }


 
public   void  insertTree(BinaryTree root,  int  data)  { // 插入节点
   if  (data  >=  root.data)  {
   
if  (root.rightpoiter  ==   null {
    root.rightpoiter 
=   new  BinaryTree(data);
   }
  else   {
    insertTree(root.rightpoiter, data);
   }

  }
  else   {
   
if  (root.leftpoiter  ==   null {
    root.leftpoiter 
=   new  BinaryTree(data);
   }
  else   {
    insertTree(root.leftpoiter, data);
   }

  }

 }

}

//  end

讲解:一个寻找关键字--searchkey
另一个是插入一个结点:insertTree
另外这是一个完全的先序遍历二叉树的语法。先根结点,再左结点,如无再右结点,如些加归至搜索完毕。  

posted on 2007-02-27 11:41 保尔任 阅读(399) 评论(0)  编辑  收藏 所属分类: Arithmetic & Data Structure

只有注册用户登录后才能发表评论。


网站导航:
 

<2007年2月>
28293031123
45678910
11121314151617
18192021222324
25262728123
45678910

常用链接

留言簿(4)

随笔分类

随笔档案

文章分类

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜