Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package prep_33_binarysearchtrees;
- public class BST_delete {
- /* Class containing left and right child of current node and key value */
- public class Node {
- int key;
- Node left, right;
- public Node(int item) {
- key = item;
- left = right = null;
- }
- }
- // Root of BST
- public Node root;
- // Constructor
- public BST_delete() {
- root = null;
- }
- // This method mainly calls deleteRec()
- public void deleteKey(int key) {
- root = deleteRec(root, key);
- }
- /* A recursive function to insert a new key in BST */
- public Node deleteRec(Node root, int key) {
- if (root == null) // Base Case: If the tree is empty
- return root;
- if (key < root.key) // Otherwise, recur down the tree
- root.left = deleteRec(root.left, key);
- else if (key > root.key)
- root.right = deleteRec(root.right, key);
- // if key is same as root's key, then This is the node
- // to be deleted
- else {
- // node with only one child or no child
- if (root.left == null)
- return root.right;
- else if (root.right == null)
- return root.left;
- // node with two children: Get the inorder successor (smallest
- // in the right subtree)
- root.key = minValue(root.right);
- // Delete the inorder successor
- root.right = deleteRec(root.right, root.key);
- }
- return root;
- }
- public int minValue(Node root) {
- int minv = root.key;
- while (root.left != null) {
- minv = root.left.key;
- root = root.left;
- }
- return minv;
- }
- // This method mainly calls insertRec()
- public void insert(int key) {
- root = insertRec(root, key);
- }
- /* A recursive function to insert a new key in BST */
- public Node insertRec(Node root, int key) {
- if (root == null) { // If the tree is empty, return a new node
- root = new Node(key);
- return root;
- }
- if (key < root.key) // Otherwise, recur down the tree
- root.left = insertRec(root.left, key);
- else if (key > root.key)
- root.right = insertRec(root.right, key);
- return root; // return the (unchanged) node pointer
- }
- // This method mainly calls InorderRec()
- public void inorder() {
- inorderRec(root);
- }
- // A utility function to do inorder traversal of BST
- public void inorderRec(Node root) {
- if (root != null) {
- inorderRec(root.left);
- System.out.print(root.key + " ");
- inorderRec(root.right);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment