Tree.java

Iz E-študij, proste zakladnice študentskega znanja

Skoči na: navigacija, iskanje
//Drevo
 
public abstract class Tree {
   public abstract TreeNode parent(TreeNode n) ;
   public abstract TreeNode leftmostChild(TreeNode n) ;
   public abstract TreeNode rightSibling(TreeNode n) ;
   public abstract void create(Object v, ListLinked subTrees) ;
   public abstract TreeNode root() ;
   public abstract void makenull() ;
   public Object label(TreeNode n) {
     return n.element ;
   }
   public int height(TreeNode n) {
     if (n==null)
       return 0 ;
     else
         return Math.max(height(leftmostChild(n))+1,
                    height(rightSibling(n))) ;
   }
   public void preorder(TreeNode r) {
     if (r != null) {
       r.writeLabel() ; System.out.print(", ") ;
       TreeNode n = leftmostChild(r) ;
       while (n != null) {
         preorder(n) ;
         n = rightSibling(n) ;
       }
     }
   }
   public void postorder(TreeNode r) {
     if (r != null) {
       TreeNode n = leftmostChild(r) ;
       while (n != null) {
         preorder(n) ;
         n = rightSibling(n) ;
       }
       r.writeLabel() ; System.out.print(", ") ;
     }
   }
   public void inorder(TreeNode r) {
     if (r != null) {
       TreeNode n = leftmostChild(r) ;
       inorder(n) ;
       r.writeLabel() ; System.out.print(", ") ;
       n = rightSibling(n) ;
       while (n != null) {
         inorder(n) ;
         n = rightSibling(n) ;
       }
     }
   }
   private boolean printLevel(int l, TreeNode r) {
      if (r==null)
        return false ;
      else if (l==1) {
        r.writeLabel(); System.out.print(", ") ;
        return true ;
      }
      else {
        TreeNode n = leftmostChild(r) ;
        boolean existsLevel = false ;
        while (n !=null) {
          existsLevel |= printLevel(l-1, n) ;
          n = rightSibling(n) ;
        }
        return existsLevel ;
      }
   }
   public void printByLevel() {
     int l = 1 ;
     while (printLevel(l,root())) {
       l++ ;
       System.out.println() ;
     }
  }
}
Vzpostavljeno iz »http://www.e-studij.si/Tree.java«
Osebna orodja
Imenski prostori
Različice
Dejanja
navigacija

Tiskanje/izvoz
orodja