public Node <int> searchRecursive(Node <int> root, int key) { //base case is root null or key found if (root == null || root.getData().Equals(key)) { return(root); } //if key less than root key, traverse left subtree if (key < root.getData()) { return(searchRecursive(root.getLeft(), key)); } //if key greater than root key, traverse right subtree return(searchRecursive(root.getRight(), key)); }
//first level, then second level, etc public void breadthFirst() { Queue <Node <int> > queue = new Queue <Node <int> >(); if (root == null) { return; } queue.Enqueue(root); //use a queue to list the nodes breadth first while (queue.Count != 0) { Node <int> n = queue.Dequeue(); Console.Write(n.getData() + " "); //if we have left node, add it to the end of the queue if (n.getLeft() != null) { queue.Enqueue(n.getLeft()); } //if we have right node, add it to the end of the queue if (n.getRight() != null) { queue.Enqueue(n.getRight()); } } }
public Node <int> insertRecursive(Node <int> root, Node <int> parent, int key) { if (root == null) { return(new Node <int>(parent, key)); } if (key < root.getData()) { root.setLeft(insertRecursive(root.getLeft(), root, key)); } else if (key > root.getData()) { root.setRight(insertRecursive(root.getRight(), root, key)); } return(root); }
public Node <int> deleteRecursive(Node <int> root, int key) { if (root == null) { return(root); } //if key less than root key, traverse left subtree if (key < root.getData()) { root.setLeft(deleteRecursive(root.getLeft(), key)); } //if key greater than root key, traverse right subtree else if (key > root.getData()) { root.setRight(deleteRecursive(root.getRight(), key)); } //found node to delete else { //node to delete has zero or one child node if (root.getLeft() == null) { if (root.getRight() != null) { root.getRight().setParent(root.getParent()); } return(root.getRight()); } else if (root.getRight() == null) { if (root.getLeft() != null) { root.getLeft().setParent(root.getParent()); } return(root.getLeft()); } //node to delete has two children, so find the smallest node on the right subtree //replace the node to delete with that node, then delete the smallest node on the right subtree root.setData(getMinValue(root.getRight())); root.setRight(deleteRecursive(root.getRight(), root.getData())); } return(root); }
//get smallest key from a tree public int getMinValue(Node <int> root) { int minValue = root.getData(); while (root.getLeft() != null) { minValue = root.getLeft().getData(); root = root.getLeft(); } return(minValue); }
public void printPostOrder(Node <int> root) { if (root == null) { return; } //traverse left subtree recursively printPostOrder(root.getLeft()); //traverse right subtree recursively printPostOrder(root.getRight()); //root node Console.Write(root.getData() + " "); }