Advertisement
DulcetAirman

Tree

Oct 10th, 2012
118
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.fhnw.claudemartin.algd2;
  2.  
  3. public class Baum {
  4.  
  5.   public static void main(String[] args) {
  6.     int[] arr = new int[16];
  7.    
  8.     for (int x = 0; x<arr.length; x++)
  9.       arr[x] = x+1;
  10.    
  11.     Node root = buildTree(arr, 0, arr.length-1);
  12.     System.out.println("root="+root);
  13.     System.out.println("trav:");
  14.     traverse(root);
  15.    
  16.   }
  17.  
  18.   static Node buildTree(int[] values, int start, int end) {
  19.     final int median = (start+end)/2;
  20.     final Node newRoot = new Node(values[median]);
  21.     if(median > start)
  22.       newRoot.left = buildTree(values, start, median-1);
  23.     if(median < end)
  24.       newRoot.right = buildTree(values, median+1, end);
  25.     return newRoot;
  26.   }
  27.  
  28.   static class Node {
  29.     public Node(Node n) {
  30.       this.key = n.key;
  31.       this.left = n.left;
  32.       this.right = n.right;
  33.     }
  34.     public Node(int key) {
  35.       this.key = key;
  36.     }
  37.     public Node(int key, Node left, Node right) {
  38.       super();
  39.       this.key = key;
  40.       this.left = left;
  41.       this.right = right;
  42.     }
  43.     public final int key;
  44.     public Node left;
  45.     public Node right;
  46.     @Override
  47.     public String toString() {
  48.       return "k="+key+" l="+(left!=null?left.key:"null")+" r="+(right!=null?right.key:"null");
  49.     }
  50.   }
  51.  
  52.   static void traverse(Node node) {
  53.     if(node != null) {
  54.       traverse(node.left);
  55.       visit(node);
  56.       traverse(node.right);
  57.     }
  58.   }
  59.  
  60.   static void visit(Node node) {
  61.     System.out.println(node.toString());
  62.   }
  63. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement