1 19 20 package org.polepos.circuits.sepang; 21 22 23 public class Tree { 24 25 private static long idGenerator; 26 27 public long id; 28 public Tree preceding; 29 public Tree subsequent; 30 public String name; 31 public int depth; 32 33 public Tree(){ 34 } 35 36 public Tree(long id, String name, int depth){ 37 this.id = id; 38 this.name = name; 39 this.depth = depth; 40 } 41 42 public static Tree createTree(int depth){ 43 idGenerator = 0; 44 return createTree(depth, 0); 45 } 46 47 private static Tree createTree(int maxDepth, int currentDepth){ 48 49 if(maxDepth <= 0){ 50 return null; 51 } 52 53 Tree tree = new Tree(); 54 if(currentDepth == 0){ 55 tree.name = "root"; 56 }else{ 57 tree.name = "node at depth " + currentDepth; 58 } 59 tree.id = ++idGenerator; 60 tree.depth = currentDepth; 61 tree.preceding = createTree(maxDepth - 1, currentDepth + 1); 62 tree.subsequent = createTree(maxDepth - 1, currentDepth + 1); 63 return tree; 64 } 65 66 public static void traverse(Tree tree, TreeVisitor visitor){ 67 if(tree == null){ 68 return; 69 } 70 traverse(tree.preceding, visitor); 71 traverse(tree.subsequent, visitor); 72 visitor.visit(tree); 73 } 74 75 public int getDepth(){ 76 return depth; 77 } 78 79 } 80 | Popular Tags |