java中二叉树的“自编、自导、自演”

来源:互联网 发布:怎么判断淘宝竞争 编辑:程序博客网 时间:2024/04/27 18:02

public class Tree {
   private Nodenew root;
   public Tree(){
    root = null;
   }
   public void insert(int data){
    Nodenew newNode = new Nodenew(data);            
       if(root == null){
        root = newNode;
       }else{
        Nodenew current = root;      
           Nodenew parent;
           while(true){
            parent = current;
               if(newNode.data < current.data) 
                  {
                   current = current.leftChild;
                  if(current == null)
                     {               
                   parent.leftChild = newNode;
                 
                      break;
                     }
                  }
               else                  
                  {
                  current = current.rightChild;
                  if(current == null)
                     {               
                   parent.rightChild = newNode;
                 
                      break;
                     }
                  } 
               } 
            } 
         }
   /*
    * 前序遍历
    */
   private void frontOrder(Nodenew localRoot)
   {
   if(localRoot != null)
      {
    System.out.print(localRoot.data + " ");
       frontOrder(localRoot.leftChild);
       frontOrder(localRoot.rightChild);
      }
   }
   /*
    * 中序遍历
    */
   private void inOrder(Nodenew localRoot)
   {
   if(localRoot != null)
      {
      inOrder(localRoot.leftChild);
      System.out.print(localRoot.data + " ");
      inOrder(localRoot.rightChild);
      }
   }
   /*
    * 后序遍历
    */
   private void endOrder(Nodenew localRoot)
   {
   if(localRoot != null)
      {
      endOrder(localRoot.leftChild);
      endOrder(localRoot.rightChild);
      System.out.print(localRoot.data + " ");
      }
   }

    //main 函数
     public static void main(String[] args){
      Tree tree = new Tree();
      tree.insert(10);
      tree.insert(16);
      tree.insert(15);
      tree.insert(2);
      tree.insert(4);
      tree.insert(20);
      tree.insert(9);
      tree.insert(18);
      tree.frontOrder(tree.root);
      System.out.println();
      tree.inOrder(tree.root);
      System.out.println();
      tree.endOrder(tree.root);
    }
}
/*
 * 结点类
 */
class Nodenew{
 public int data;
 public Nodenew leftChild;
 public Nodenew rightChild;
 public Nodenew next;
 public Nodenew(int data){
  this.data = data;
  this.leftChild = null;
  this.rightChild = null;
 }
}

原创粉丝点击