public static boolean find(Tree node, int value) { count++; if (value == node.getValue()) { System.out.println(count); return true; } if (value < node.getValue() && node.getLeft() != null) { return find(node.getLeft(), value); } if (value > node.getValue() && node.getRight() != null) { return find(node.getRight(), value); } return false; }
public static void insert(Tree node, int value) { if (node.left == null && node.right == null && node.getValue() == 0) { node.setValue(value); return; } Tree newNode = new Tree(); newNode.setValue(value); if (value < node.getValue() && node.getLeft() == null) { node.setLeft(newNode); return; } else if (value < node.getValue() && node.getLeft() != null) { insert(node.getLeft(), value); } else if (value > node.getValue() && node.getRight() == null) { node.setRight(newNode); return; } else if (value > node.getValue() && node.getRight() != null) { insert(node.getRight(), value); } return; }
@Override public boolean acceptsChild(Tree<JsonTreeNode> child) { // Only non-null children are allowed. if (child == null) { return false; } // Only arrays or objects can have children. if (getValue().getType() != JsonTreeNode.ElementType.ARRAY && getValue().getType() != JsonTreeNode.ElementType.OBJECT) { return false; } // Additionally, only objects can have child key-value pairs. if (getValue().getType() == JsonTreeNode.ElementType.ARRAY && child.getValue().getType() == JsonTreeNode.ElementType.KEY_VALUE_PAIR) { return false; } return true; }
/* Search for n in a tree t, and return the subtree whose root is n * If n does not occur in the tree, throw an exception. */ public static Tree find(int n, Tree t) { if (t.getEmpty()) throw new IllegalArgumentException("Value not present in search" + " tree"); else if (n == t.getValue()) return t; else if (n < t.getValue()) return find(n, t.getLeft()); else return find(n, t.getRight()); }
/* Insert n into a tree t in order, and return the resulting tree. */ public static Tree insert(int n, Tree t) { if (t.getEmpty()) return new Tree(n, new Tree(), new Tree()); else if (n <= t.getValue()) return new Tree(t.getValue(), insert(n, t.getLeft()), t.getRight()); else return new Tree(t.getValue(), t.getLeft(), insert(n, t.getRight())); }
/** Test method for {@link com.fuerve.whiteboard.milestone2.structures.Tree#getValue()}. */ @Test public void testGetSetValue() { final Tree<Integer> target = new Tree<Integer>(); target.setValue(1); assertEquals(new Integer(1), target.getValue()); }