// recursive support method for above private BSTNode delete(T item, BSTNode current) { // if current is null, nothing new to return if (current != null) { // if item is smaller, go left if (item.compareTo(current.element) < 0) { current.left = delete(item, current.left); } // if item is larger, go right else if (item.compareTo(current.element) > 0) { current.right = delete(item, current.right); } else { // get smallest of right subtree, then delete this node if (current.left != null && current.right != null) { current.element = findMinimum(current.right); current.right = delete(current.element, current.right); } // if only left child, replace with this else if (current.left != null && current.right == null) { current = current.left; } // if only right child, replace with this else if (current.left == null && current.right != null) { current = current.right; } else { // if no children, delete node by setting to null current = null; } } } return current; }
private void printDepthFirstTraversalRec(BSTNode t) { if (t != null) { System.out.println(t.getInfo()); printDepthFirstTraversalRec(t.getLeft()); printDepthFirstTraversalRec(t.getRight()); } }
private void postOrder(BSTNode<T> tree) // Initializes postOrderQueue with tree elements in postOrder order. { if (tree != null) { postOrder(tree.getLeft()); postOrder(tree.getRight()); postOrderQueue.enqueue(tree.getInfo()); } }
/* * formacion del arbol */ private void continueRotation(BSTNode gr, BSTNode par, BSTNode ch, BSTNode desc) { if (gr != null) { // if par has a grandparent; if (gr.right == ((SplayTreeNode) ch).parent) gr.right = ch; else gr.left = ch; } else root = ch; if (desc != null) ((SplayTreeNode) desc).parent = par; ((SplayTreeNode) par).parent = ch; ((SplayTreeNode) ch).parent = gr; }
private boolean recContains(T element, BSTNode<T> tree) // Returns true if tree contains an element e such that // e.compareTo(element) == 0; otherwise, returns false. { if (tree == null) return false; // element is not found else if (element.compareTo(tree.getInfo()) < 0) return recContains(element, tree.getLeft()); // Search left subtree else if (element.compareTo(tree.getInfo()) > 0) return recContains(element, tree.getRight()); // Search right subtree else return true; // element is found }
private T recGet(T element, BSTNode<T> tree) // Returns an element e from tree such that e.compareTo(element) == 0; // if no such element exists, returns null. { if (tree == null) return null; // element is not found else if (element.compareTo(tree.getInfo()) < 0) return recGet(element, tree.getLeft()); // get from left subtree else if (element.compareTo(tree.getInfo()) > 0) return recGet(element, tree.getRight()); // get from right subtree else return tree.getInfo(); // element is found }
private BSTNode<T> recAdd(T element, BSTNode<T> tree) // Adds element to tree; tree retains its BST property. { if (tree == null) // Addition place found tree = new BSTNode<T>(element); else if (element.compareTo(tree.getInfo()) <= 0) tree.setLeft(recAdd(element, tree.getLeft())); // Add in left subtree else tree.setRight(recAdd(element, tree.getRight())); // Add in right subtree return tree; }
public BSTNode minBST(int[] array, int start, int end) { if (start > end) { return null; } int mid = (start + end) / 2; BSTNode n = new BSTNode(array[mid]); size++; n.left = minBST(array, start, mid - 1); n.right = minBST(array, mid + 1, end); return n; }
public boolean remove(int x) { BSTNode current = root; BSTNode parent = null; boolean branch = true; // true =left, false =right while (current != null) { if (current.value == x) { BSTNode bigson = current; while (bigson.left != null || bigson.right != null) { parent = bigson; if (bigson.right != null) { bigson = bigson.right; branch = false; } else { bigson = bigson.left; branch = true; } } // System.out.println("Remove: current "+current.value+" parent "+parent.value+" bigson // "+bigson.value); if (parent != null) { if (branch) { parent.left = null; } else { parent.right = null; } } if (bigson != current) { current.value = bigson.value; } else {; } return true; } parent = current; // if (current.value <x ) { // THERE WAS ERROR if (current.value > x) { current = current.left; branch = true; } else { current = current.right; branch = false; } } return false; }
public static void traverseBSTIterativeInOrder(BSTNode<Integer> root) { Stack<BSTNode<Integer>> stack = new Stack<BSTNode<Integer>>(); stack.push(root); while (!stack.empty()) { BSTNode<Integer> current = stack.pop(); if (current == null) { continue; } if (!current.visited) { current.visited = true; stack.push(current.right); stack.push(current); stack.push(current.left); } else { System.out.println(current.data); } } }
public int size2() // Returns the number of elements in this BST. { int count = 0; if (root != null) { LinkedStack<BSTNode<T>> hold = new LinkedStack<BSTNode<T>>(); BSTNode<T> currNode; hold.push(root); while (!hold.isEmpty()) { currNode = hold.top(); hold.pop(); count++; if (currNode.getLeft() != null) hold.push(currNode.getLeft()); if (currNode.getRight() != null) hold.push(currNode.getRight()); } } return count; }
private BSTNode<T> removeNode(BSTNode<T> tree) { T data; if (tree.getLeft() == null) return tree.getRight(); else if (tree.getRight() == null) return tree.getLeft(); else { data = getPredecessor(tree.getLeft()); tree.setInfo(data); tree.setLeft(recRemove(data, tree.getLeft())); return tree; } }
/** * Add <tt>element</tt> to the tree. * * @param parent parent of <tt>node</tt> * @param node root of subtree to which element is to be added * @param element the element to be added to the tree * @throws SearchTreeException if node is found in the tree */ protected BSTNode<E> add(BSTNode<E> parent, BSTNode<E> node, E element) { if (node == null) { // base case node = new AVLNode(element); node.parent = parent; } else { // recursive case int compareResult = element.compareTo(node.getElement()); if (compareResult < 0) { node.leftChild = add(node, node.leftChild, element); } else if (compareResult > 0) { node.rightChild = add(node, node.rightChild, element); } else { throw new SearchTreeException("Duplicate element: " + element.toString()); } // now do height/balance updates and possible // subtree fixes node = fixSubtreeRootedAt((AVLNode<E>) node); } return node; }
// recusive support method for above private BSTNode insert(T item, BSTNode current) { // if current node does not exist, make new node for item if (current == null) { current = new BSTNode(item, null, null); } // if new item is smaller, go to the left else if (item.compareTo(current.element) < 0) { current.left = insert(item, current.left); } // if new item is larger, go to the right else if (item.compareTo(current.element) > 0) { current.right = insert(item, current.right); } // otherwise we have duplicate and throw exception else { throw new MyException("Duplicate item"); } return current; }
/** * Determine if this tree contains <tt>element</tt>. * * @param element the element we are looking for in the tree. * @return <tt>true</tt> if <tt>element</tt> is found in this tree, <tt>false</tt> otherwise. */ protected boolean contains(BSTNode<E> node, E element) { if (node == null) { return false; } int compareResult = element.compareTo(node.getElement()); if (compareResult < 0) { return contains(node.leftChild, element); } else if (compareResult > 0) { return contains(node.rightChild, element); } else { return true; } }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BSTNode that = (BSTNode) o; if (data != null ? !data.equals(that.data) : that.data != null) { return false; } if (left != null ? !left.equals(that.left) : that.left != null) { return false; } if (right != null ? !right.equals(that.right) : that.right != null) { return false; } return true; }
public void add(int x) { BSTNode current = root; if (root == null) { root = new BSTNode(x); return; } while (current.value != x) { if (x < current.value) { if (current.left == null) { current.left = new BSTNode(x); } else { current = current.left; } } else { if (current.right == null) { current.right = new BSTNode(x); } else { current = current.right; } } } }
public void printBreadthFirstTraversal() { BSTNode b; LinkedUnbndQueue<BSTNode> q = new LinkedUnbndQueue<BSTNode>(); q.enqueue(root); while (!q.isEmpty()) { b = q.dequeue(); System.out.println(b.getInfo()); if (b.getLeft() != null) q.enqueue(b.getLeft()); if (b.getRight() != null) q.enqueue(b.getRight()); } }
private BSTNode<T> recRemove(T element, BSTNode<T> tree) { if (tree == null) found = false; else if (element.compareTo(tree.getInfo()) < 0) tree.setLeft(recRemove(element, tree.getLeft())); else if (element.compareTo(tree.getInfo()) > 0) tree.setRight(recRemove(element, tree.getRight())); else { tree = removeNode(tree); found = true; } return tree; }
public void printDepthFirstTraversal() { BSTNode b; LinkedStack<BSTNode> s = new LinkedStack<BSTNode>(); s.push(root); while (!s.isEmpty()) { b = s.top(); s.pop(); System.out.println(b.getInfo()); if (b.getRight() != null) s.push(b.getRight()); if (b.getLeft() != null) s.push(b.getLeft()); } }
/** * Remove element from this tree. * * @param nodethe root of the subtree from which to remove element. * @param element the element to remove. */ protected BSTNode<E> remove(BSTNode<E> node, E target) { if (node == null) { // element isn't in the tree return null; } int compareResult = target.compareTo(node.getElement()); if (compareResult < 0) { node.leftChild = remove(node.leftChild, target); node = fixSubtreeRootedAt((AVLNode<E>) node); } else if (compareResult > 0) { node.rightChild = remove(node.rightChild, target); node = fixSubtreeRootedAt((AVLNode<E>) node); } else { // found the target! this.size--; // handle the case of two children first if ((node.leftChild != null) && (node.rightChild != null)) { BSTNode<E> replacement = successor(node); node.setElement(replacement.getElement()); // now deal with removing the replacement BSTNode<E> newChild = replacement.leftChild == null ? replacement.rightChild : replacement.leftChild; if (replacement == replacement.parent.leftChild) { replacement.parent.leftChild = newChild; } else { replacement.parent.rightChild = newChild; } // now fix the height/balance from the replacement's // parent to node // if, along the way, we find a subtree unbalanced, // rebalance it node = updatePath((AVLNode<E>) node, replacement.parent.getElement()); } else { // Collapse the cases of no children and 1 child node = (node.leftChild == null) ? node.rightChild : node.leftChild; } } return node; }
public static void main(String[] args) { /** array to be inserted in BSTSort and values that will be inserted in the BinarySearchTree */ int[] values = { 2, 5, 33, 532, 543, 63, 451, 61, 4, 6, 22, 46, 1, 4, 12, 41, 456, 23, 51, 35, 6, 12 }; /** BSTSorted tree */ System.out.println("BST Ordered Tree: "); BSTSort(values); System.out.println(" "); /** Empty BinarySearchTree */ BinarySearchTree tree = new BinarySearchTree(); /** * iterates through the array and inserts a value from the array into the newly formed * BinarySearchTree */ for (int i = 0; i < values.length; i++) { tree.insert(new BSTNode(values[i])); } /** PostOrder Sorted Tree */ System.out.println("Post Order: "); tree.postOrder(); System.out.println(""); /** PreOrder Sorted Tree */ System.out.println("Pre Order: "); tree.preOrder(); System.out.println(""); /** Size of Tree after values have been inserted */ System.out.println("Current Size: "); System.out.println(tree.getSize()); /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value1 = tree.search(5); if (value1 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value1.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value2 = tree.search(33); if (value2 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value2.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value3 = tree.search(451); if (value3 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value3.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value4 = tree.search(6); if (value4 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value4.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value5 = tree.search(1); if (value5 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value5.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value6 = tree.search(333); if (value6 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value6.getKey()); } BSTNode value7 = tree.search(342334); if (value7 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value7.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value8 = tree.search(43323); if (value8 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value8.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value9 = tree.search(89687); if (value9 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value9.getKey()); } /** * Search for values in the tree. If a value is not found, a message will be printed to notify * the user. */ BSTNode value10 = tree.search(10000); if (value10 == null) { System.out.println("Not found."); } else { System.out.println("Found it " + value10.getKey()); } /** Prints the values of the tree from smallest to largest */ System.out.println("Ascending Order: "); BSTNode current = tree.minimum(); for (int i = 0; i < tree.getSize(); i++) { System.out.print(" " + current.toString()); current = tree.successor(current); } System.out.println(" "); /** Prints the values of the tree from largest to smallest */ System.out.println("Descending Order: "); BSTNode current1 = tree.maximum(); for (int i = 0; i < tree.getSize(); i++) { System.out.print(" " + current1.toString()); current1 = tree.predecessor(current1); } System.out.println(" "); /** Deleting a few values and nodes from the tree */ tree.delete(tree.search(61)); tree.delete(tree.search(6)); tree.delete(tree.search(46)); /** Returns size of the altered tree */ System.out.println("Current Size: "); System.out.println(tree.getSize()); /** Rearranges the altered tree using inOrder travels */ System.out.println("In Order: "); System.out.print(" "); tree.inOrder(); /** testing the BSTSort with trees of different sizes */ int[] values2 = {4, 56, 7, 1, 3, 7}; System.out.println(" "); System.out.println("BST Ordered Tree: "); BSTSort(values2); /** testing the BSTSort with trees of different sizes */ int[] values3 = {33, 2, 1}; System.out.println(" "); System.out.println("BST Ordered Tree: "); BSTSort(values3); /** testing the BSTSort with trees of different sizes */ int[] values4 = {3, 4, 5, 3, 3, 522, 454, 621}; System.out.println(" "); System.out.println("BST Ordered Tree: "); BSTSort(values4); /** testing the BSTSort with trees of different sizes */ int[] values5 = {3, 231, 5, 3, 3, 5443322, 434, 621, 6, 78, 9, 54345, 64}; System.out.println(" "); System.out.println("BST Ordered Tree: "); BSTSort(values5); /** testing the BSTSort with trees of different sizes */ int[] values6 = {5, 4, 3, 2, 1, 0, -1, -2, -3}; System.out.println(" "); System.out.println("BST Ordered Tree: "); BSTSort(values6); /** testing the BSTSort with trees of different sizes */ int[] values7 = {5}; System.out.println(" "); System.out.println("BST Ordered Tree: "); BSTSort(values7); }
public BSTNode(BSTNode root) { this(root.getData(), root.getLeft(), root.getRight()); } // copy root constructor
private int recSize(BSTNode<T> tree) // Returns the number of elements in tree. { if (tree == null) return 0; else return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1; }
public RegBST<Integer, String> genRemove() { RegBST<Integer, String> tree = new RegBST<Integer, String>(); BSTNode<Integer, String> a = new BSTNode<Integer, String>(30, "a"); BSTNode<Integer, String> b = new BSTNode<Integer, String>(17, "b"); BSTNode<Integer, String> c = new BSTNode<Integer, String>(55, "c"); BSTNode<Integer, String> d = new BSTNode<Integer, String>(5, "d"); BSTNode<Integer, String> e = new BSTNode<Integer, String>(45, "e"); BSTNode<Integer, String> f = new BSTNode<Integer, String>(67, "f"); BSTNode<Integer, String> g = new BSTNode<Integer, String>(3, "g"); BSTNode<Integer, String> h = new BSTNode<Integer, String>(10, "h"); BSTNode<Integer, String> i = new BSTNode<Integer, String>(31, "i"); BSTNode<Integer, String> j = new BSTNode<Integer, String>(47, "j"); BSTNode<Integer, String> k = new BSTNode<Integer, String>(60, "k"); BSTNode<Integer, String> l = new BSTNode<Integer, String>(4, "l"); BSTNode<Integer, String> m = new BSTNode<Integer, String>(9, "m"); BSTNode<Integer, String> n = new BSTNode<Integer, String>(46, "n"); BSTNode<Integer, String> o = new BSTNode<Integer, String>(58, "o"); BSTNode<Integer, String> p = new BSTNode<Integer, String>(63, "p"); BSTNode<Integer, String> q = new BSTNode<Integer, String>(62, "q"); a.setLeft(b); a.setRight(c); b.setLeft(d); c.setLeft(e); c.setRight(f); d.setLeft(g); d.setRight(h); e.setLeft(i); e.setRight(j); f.setLeft(k); g.setRight(l); h.setLeft(m); j.setLeft(n); k.setLeft(o); k.setRight(p); p.setLeft(q); tree.setRoot(a); return tree; }
private T getPredecessor(BSTNode<T> tree) // Returns the information held in the rightmost node in tree { while (tree.getRight() != null) tree = tree.getRight(); return tree.getInfo(); }
public static void main(String[] args) { BSTNode bn = new BSTNode(); TNode root = null; root = bn.insert(root, 50); root = bn.insert(root, 30); root = bn.insert(root, 20); root = bn.insert(root, 40); root = bn.insert(root, 70); root = bn.insert(root, 60); root = bn.insert(root, 80); if (bn.bstsearch(root, 30)) { System.out.println("Key Found"); } else { System.out.println("Key Not Found"); } System.out.print("InOrder Traversal: "); bn.inorder(root); System.out.print("\nPreOrder Traversal: "); bn.preorder(root); System.out.print("\nPostOrder Traversal: "); bn.postorder(root); System.out.println("\nMinimum value node in BST is: " + bn.minvaluenode(root).data); System.out.println("Maximum value node in BST is: " + bn.maxvaluenode(root).data); // bn.delete(root, 40); bn.inorder(root); TNode pre = null; TNode succ = null; // bn.findpresucc(root, pre, succ, 40); TNode a = new TNode(4); a.left = new TNode(2); TNode b = a.left; a.right = new TNode(5); TNode c = a.right; a.left.left = new TNode(1); TNode d = a.left.left; a.left.right = new TNode(3); TNode e = a.left.right; bn.inorder(a); System.out.println("\nIs BST???: " + bn.isBST(a)); System.out.println("IS BST Efficient: " + bn.isbstefficient(root)); System.out.println("Lowes Common Ancestor of 20 and 40 is: " + bn.lca(root, 20, 40).data); System.out.println( "Lowes Common Ancestor of 20 and 40 without recurse is: " + bn.lcanorecurse(root, 20, 40).data); int[] intarr = {4, 2, 5, 1, 3}; int start = 0; int end = intarr.length - 1; System.out.print("Sorted array is: "); bn.printSortedarray(intarr, start, end); System.out.println( "\nInOrder Successor of " + d.data + " is: " + bn.InOrderSuccessor(a, d).data); System.out.println( "\nInOrder Predecessor of " + c.data + " is: " + bn.InOrderPredecessor(a, c).data); int k = 2; System.out.print(k + "th smallest element in BST is: "); bn.kthsmallest(a, k); System.out.print("\nBST Keys in the range are: "); bn.bstrange(root, 20, 75); System.out.print("\nBST Keys in the range using Recursion are: "); bn.bstrangerecurse(root, 5, 75); System.out.println(); int[] sortarr = {1, 2, 3, 4, 5, 6, 7}; System.out.println(); TNode newroot = bn.SortedArrayToBST(sortarr, 0, sortarr.length - 1); bn.inorder(newroot); System.out.println("\nSize of largest BST is: " + bn.largestbst(a)); int[] arr1 = {8, 3, 6, 1, 4, 7, 10, 14, 13}; int arr2[] = {8, 10, 14, 3, 6, 4, 1, 7, 13}; System.out.println( "\n Identical BST's from arrays?? " + bn.identicalBSTcheckfromArrays(arr1, arr2, arr1.length, arr2.length)); System.out.print("InOrder is: "); bn.inorder(root); bn.addSum(root, 0); System.out.print("\nAfter adding greater values to every Node, InOrder is: "); bn.inorder(root); int[] arr = {8, 3, 5, 7, 6}; System.out.println("\nHas Only one Child?? " + bn.HasOnlyOneChild(arr)); /*bn.inorder(a); a = bn.RemoveNodesOutOfRange(a, 2, 4); System.out.println(); bn.inorder(a);*/ TNode neww = null; neww = bn.MergeTreesUtil(a, root); System.out.print("InOrder Travesal of Merged Trees is: "); bn.inorder(neww); System.out.println("\nVertical Order of Tree: "); TNode n1 = new TNode(1); n1.left = new TNode(2); n1.right = new TNode(3); n1.left.left = new TNode(4); n1.left.right = new TNode(5); n1.right.left = new TNode(6); n1.right.right = new TNode(7); n1.right.left.right = new TNode(8); n1.right.right.right = new TNode(9); bn.PrintVertical(n1); TNodeMethods tm = new TNodeMethods(); tm.doubletr(n1); bn.inorder(n1); }
public void testPreorder() { BSTNode<String, String> one = new BSTNode<String, String>("a", "1"); BSTNode<String, String> two = new BSTNode<String, String>("b", "2"); BSTNode<String, String> three = new BSTNode<String, String>("c", "3"); BSTNode<String, String> four = new BSTNode<String, String>("d", "4"); BSTNode<String, String> five = new BSTNode<String, String>("e", "5"); BSTNode<String, String> six = new BSTNode<String, String>("f", "6"); BSTNode<String, String> seven = new BSTNode<String, String>("g", "7"); BSTNode<String, String> eight = new BSTNode<String, String>("h", "8"); BSTNode<String, String> nine = new BSTNode<String, String>("i", "9"); BSTNode<String, String> ten = new BSTNode<String, String>("j", "10"); BSTNode<String, String> eleven = new BSTNode<String, String>("k", "11"); one.setLeft(two); one.setRight(three); two.setRight(seven); three.setLeft(four); three.setRight(six); four.setRight(five); six.setLeft(eight); six.setRight(nine); seven.setLeft(eleven); eight.setLeft(ten); RegBST<String, String> tree = new RegBST<String, String>(); tree.setRoot(one); assertEquals("a b g k c d e f h j i ", tree.preorder()); }