1 13 14 package com.tonbeller.jpivot.util; 15 16 import java.util.ArrayList ; 17 import java.util.Iterator ; 18 import java.util.List ; 19 20 23 public class TreeNode { 24 25 private TreeNode parent = null; 26 private List children = null; 27 private Object reference; 28 29 33 public TreeNode(Object obj) { 34 this.parent = null; 35 this.reference = obj; 36 this.children = new ArrayList (); 37 } 38 39 42 public void remove() { 43 if (parent != null) { 44 parent.removeChild(this); 45 } 46 } 47 48 52 private void removeChild(TreeNode child) { 53 if (children.contains(child)) 54 children.remove(child); 55 56 } 57 58 62 public void addChildNode(TreeNode child) { 63 child.parent = this; 64 if (!children.contains(child)) 65 children.add(child); 66 } 67 68 72 public TreeNode deepCopy() { 73 TreeNode newNode = new TreeNode(reference); 74 for (Iterator iter = children.iterator(); iter.hasNext();) { 75 TreeNode child = (TreeNode) iter.next(); 76 newNode.addChildNode(child.deepCopy()); 77 } 78 return newNode; 79 } 80 81 86 public TreeNode deepCopyPrune(int depth) { 87 if (depth < 0) 88 throw new IllegalArgumentException ("Depth is negative"); 89 TreeNode newNode = new TreeNode(reference); 90 if (depth == 0) 91 return newNode; 92 for (Iterator iter = children.iterator(); iter.hasNext();) { 93 TreeNode child = (TreeNode) iter.next(); 94 newNode.addChildNode(child.deepCopyPrune(depth - 1)); 95 } 96 return newNode; 97 } 98 99 102 public int getLevel() { 103 int level = 0; 104 TreeNode p = parent; 105 while (p != null) { 106 ++level; 107 p = p.parent; 108 } 109 return level; 110 } 111 112 116 public int walkTree(TreeNodeCallback callbackHandler) { 117 int code = 0; 118 code = callbackHandler.handleTreeNode(this); 119 if (code != TreeNodeCallback.CONTINUE) 120 return code; 121 ChildLoop: for (Iterator iter = children.iterator(); iter.hasNext();) { 122 TreeNode child = (TreeNode) iter.next(); 123 code = child.walkTree(callbackHandler); 124 if (code >= TreeNodeCallback.CONTINUE_PARENT) 125 return code; 126 } 127 return code; 128 } 129 130 134 public int walkChildren(TreeNodeCallback callbackHandler) { 135 int code = 0; 136 ChildLoop: for (Iterator iter = children.iterator(); iter.hasNext();) { 137 TreeNode child = (TreeNode) iter.next(); 138 code = callbackHandler.handleTreeNode(child); 139 if (code >= TreeNodeCallback.CONTINUE_PARENT) 140 return code; 141 if (code == TreeNodeCallback.CONTINUE) { 142 code = child.walkChildren(callbackHandler); 143 if (code > TreeNodeCallback.CONTINUE_PARENT) 144 return code; 145 } 146 } 147 return code; 148 } 149 150 153 public List getChildren() { 154 return children; 155 } 156 157 160 public TreeNode getParent() { 161 return parent; 162 } 163 164 167 public Object getReference() { 168 return reference; 169 } 170 171 175 public void setReference(Object object) { 176 reference = object; 177 } 178 179 } | Popular Tags |