The Wayback Machine - https://web.archive.org/web/20240912233859/https://www.geeksforgeeks.org/threaded-binary-search-tree-deletion/
Open In App

Threaded Binary Search Tree | Deletion

Last Updated : 11 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A threaded binary tree node looks like following.

C++




struct Node {
    struct Node *left, *right;
    int info;
 
    // false if left pointer points to predecessor
    // in Inorder Traversal
    bool lthread;
 
    // false if right pointer points to predecessor
    // in Inorder Traversal
    bool rthread;
};


Java




static class Node {
    Node left, right;
    int info;
 
    // True if left pointer points to predecessor
    // in Inorder Traversal
    boolean lthread;
 
    // True if right pointer points to predecessor
    // in Inorder Traversal
    boolean rthread;
};
 
 
// This code contributed by aashish1995


Python3




class Node:
    def __init__(self):
        self.info = 0;
        self.left = None;
        self.right = None;
         
        # True if left pointer points to predecessor
        # in Inorder Traversal
        self.lthread = False;;
     
        # True if right pointer points to predecessor
        # in Inorder Traversal
        self.rthread = False;
 
# This code contributed by umadevi9616


C#




public
  class Node
  {
    public
      Node left,
    right;
    public
      int info;
 
    // True if left pointer points to predecessor
    // in Inorder Traversal
    public
      bool lthread;
 
    // True if right pointer points to predecessor
    // in Inorder Traversal
    public
      bool rthread;
  };
 
// This code is contributed by aashish1995


Javascript




<script>
 class Node {
     constructor(){
  
     this.left = null, this.right = null;
     this.info = 0;
 
    // True if left pointer points to predecessor
    // in Inorder Traversal
    this.lthread = false;
 
    // True if right pointer points to predecessor
    // in Inorder Traversal
    this.rthread = false;
}
}
// This code contributed by aashish1995
</script>


We have already discussed Insertion of Threaded Binary Search Tree 

In deletion, first the key to be deleted is searched, and then there are different cases for deleting the Node in which key is found. 

C++




// Deletes a key from threaded BST with given root and
// returns new root of BST.
struct Node* delThreadedBST(struct Node* root, int dkey)
{
    // Initialize parent as NULL and ptrent
    // Node as root.
    struct Node *par = NULL, *ptr = root;
 
    // Set true if key is found
    int found = 0;
 
    // Search key in BST : find Node and its
    // parent.
    while (ptr != NULL) {
        if (dkey == ptr->info) {
            found = 1;
            break;
        }
        par = ptr;
        if (dkey < ptr->info) {
            if (ptr->lthread == false)
                ptr = ptr->left;
            else
                break;
        }
        else {
            if (ptr->rthread == false)
                ptr = ptr->right;
            else
                break;
        }
    }
 
    if (found == 0)
        printf("dkey not present in tree\n");
 
    // Two Children
    else if (ptr->lthread == false && ptr->rthread == false)
        root = caseC(root, par, ptr);
 
    // Only Left Child
    else if (ptr->lthread == false)
        root = caseB(root, par, ptr);
 
    // Only Right Child
    else if (ptr->rthread == false)
        root = caseB(root, par, ptr);
 
    // No child
    else
        root = caseA(root, par, ptr);
 
    return root;
}


Java




// Deletes a key from threaded BST with given root and
// returns new root of BST.
Node delThreadedBST(Node root, int dkey)
{
    // Initialize parent as null and ptrent
    // Node as root.
    Node par = null, ptr = root;
 
    // Set true if key is found
    int found = 0;
 
    // Search key in BST : find Node and its
    // parent.
    while (ptr != null) {
        if (dkey == ptr.info) {
            found = 1;
            break;
        }
        par = ptr;
        if (dkey < ptr.info) {
            if (ptr.lthread == false)
                ptr = ptr.left;
            else
                break;
        }
        else {
            if (ptr.rthread == false)
                ptr = ptr.right;
            else
                break;
        }
    }
 
    if (found == 0)
        System.out.printf("dkey not present in tree\n");
 
    // Two Children
    else if (ptr.lthread == false && ptr.rthread == false)
        root = caseC(root, par, ptr);
 
    // Only Left Child
    else if (ptr.lthread == false)
        root = caseB(root, par, ptr);
 
    // Only Right Child
    else if (ptr.rthread == false)
        root = caseB(root, par, ptr);
 
    // No child
    else
        root = caseA(root, par, ptr);
 
    return root;
}
 
// This code is contributed by gauravrajput1


Python3




# Deletes a key from threaded BST with given root and
# returns new root of BST.
def delThreadedBST(root, dkey):
 
    # Initialize parent as None and ptrent
    # Node as root.
    par = None;
    ptr = root;
 
    # Set True if key is found
    found = 0;
 
    # Search key in BST : find Node and its
    # parent.
    while (ptr != None):
        if (dkey == ptr.info):
            found = 1;
            break;
         
        par = ptr;
        if (dkey < ptr.info):
            if (ptr.lthread == False)
                ptr = ptr.left;
            else
                break;
         
        else:
            if (ptr.rthread == False)
                ptr = ptr.right;
            else
                break;
 
    if (found == 0):
        print("dkey not present in tree");
 
    # Two Children
    else if(ptr.lthread == False and ptr.rthread == False):
        root = caseC(root, par, ptr);
 
    # Only Left Child
    else if(ptr.lthread == False):
        root = caseB(root, par, ptr);
 
    # Only Right Child
    else if(ptr.rthread == False):
        root = caseB(root, par, ptr);
 
    # No child
    else:
        root = caseA(root, par, ptr);
 
    return root;
 
# This code is contributed by Rajput-Ji


C#




// Deletes a key from threaded BST with given root and
// returns new root of BST.
Node delThreadedBST(Node root, int dkey)
{
    // Initialize parent as null and ptrent
    // Node as root.
    Node par = null, ptr = root;
 
    // Set true if key is found
    int found = 0;
 
    // Search key in BST : find Node and its
    // parent.
    while (ptr != null) {
        if (dkey == ptr.info) {
            found = 1;
            break;
        }
        par = ptr;
        if (dkey < ptr.info) {
            if (ptr.lthread == false)
                ptr = ptr.left;
            else
                break;
        }
        else {
            if (ptr.rthread == false)
                ptr = ptr.right;
            else
                break;
        }
    }
 
    if (found == 0)
        Console.Write("dkey not present in tree\n");
 
    // Two Children
    else if (ptr.lthread == false && ptr.rthread == false)
        root = caseC(root, par, ptr);
 
    // Only Left Child
    else if (ptr.lthread == false)
        root = caseB(root, par, ptr);
 
    // Only Right Child
    else if (ptr.rthread == false)
        root = caseB(root, par, ptr);
 
    // No child
    else
        root = caseA(root, par, ptr);
 
    return root;
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
// Deletes a key from threaded BST with given root and
// returns new root of BST.
function delThreadedBST(root , dkey)
{
    // Initialize parent as null and ptrent
    // Node as root.
    var par = null, ptr = root;
 
    // Set true if key is found
    var found = 0;
 
    // Search key in BST : find Node and its
    // parent.
    while (ptr != null) {
        if (dkey == ptr.info) {
            found = 1;
            break;
        }
        par = ptr;
        if (dkey < ptr.info) {
            if (ptr.lthread == false)
                ptr = ptr.left;
            else
                break;
        }
        else {
            if (ptr.rthread == false)
                ptr = ptr.right;
            else
                break;
        }
    }
 
    if (found == 0)
        document.write("dkey not present in tree\n");
 
    // Two Children
    else if (ptr.lthread == false && ptr.rthread == false)
        root = caseC(root, par, ptr);
 
    // Only Left Child
    else if (ptr.lthread == false)
        root = caseB(root, par, ptr);
 
    // Only Right Child
    else if (ptr.rthread == false)
        root = caseB(root, par, ptr);
 
    // No child
    else
        root = caseA(root, par, ptr);
 
    return root;
}
 
// This code is contributed by gauravrajput1
</script>


Case A: Leaf Node need to be deleted 

In BST, for deleting a leaf Node the left or right pointer of parent was set to NULL. Here instead of setting the pointer to NULL it is made a thread. 
If the leaf Node is to be deleted is left child of its parent then after deletion, left pointer of parent should become a thread pointing to its predecessor of the parent Node after deletion. 

par -> lthread = true;
par -> left = ptr -> left;

If the leaf Node to be deleted is right child of its parent then after deletion, right pointer of parent should become a thread pointing to its successor. The Node which was inorder successor of the leaf Node before deletion will become the inorder successor of the parent Node after deletion. 

par -> rthread = true;
par -> right = ptr -> right;

C++




// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
struct Node* caseA(struct Node* root, struct Node* par,
                   struct Node* ptr)
{
    // If Node to be deleted is root
    if (par == NULL)
        root = NULL;
 
    // If Node to be deleted is left
    // of its parent
    else if (ptr == par->left) {
        par->lthread = true;
        par->left = ptr->left;
    }
    else {
        par->rthread = true;
        par->right = ptr->right;
    }
 
    // Free memory and return new root
    free(ptr);
    return root;
}


Java




// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
Node caseA(Node root, Node par,
                   Node ptr)
{
   
    // If Node to be deleted is root
    if (par == null)
        root = null;
 
    // If Node to be deleted is left
    // of its parent
    else if (ptr == par.left) {
        par.lthread = true;
        par.left = ptr.left;
    }
    else {
        par.rthread = true;
        par.right = ptr.right;
    }
 
    return root;
}
 
// This code is contributed by gauravrajput1


Python3




# Here 'par' is pointer to parent Node and 'ptr' is
# pointer to current Node.
def caseA(root,par,ptr):
   
  # If Node to be deleted is root
    if (par == None):
        root = None
         
     # If Node to be deleted is left
    # of its parent
    elif(ptr == par.left):
        par.lthread = true
        par.left = ptr.left
    else:
        par.rthread = true
        par.right = ptr.right
return root
 
# This code is contributed by Patel2127.


C#




// Here 'par' is pointer to parent Node and
// 'ptr' is pointer to current Node.
Node caseA(Node root, Node par, Node ptr)
{
     
    // If Node to be deleted is root
    if (par == null)
        root = null;
 
    // If Node to be deleted is left
    // of its parent
    else if (ptr == par.left)
    {
        par.lthread = true;
        par.left = ptr.left;
    }
    else
    {
        par.rthread = true;
        par.right = ptr.right;
    }
    return root;
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// Here 'par' is pointer to parent Node and
// 'ptr' is pointer to current Node.
function caseA(root, par, ptr)
{
     
    // If Node to be deleted is root
    if (par == null)
        root = null;
  
    // If Node to be deleted is left
    // of its parent
    else if (ptr == par.left)
    {
        par.lthread = true;
        par.left = ptr.left;
    }
    else
    {
        par.rthread = true;
        par.right = ptr.right;
    }
    return root;
}
 
// This code is contributed by rag2127
 
</script>


Case B: Node to be deleted has only one child 
After deleting the Node as in a BST, the inorder successor and inorder predecessor of the Node are found out. 

s = inSucc(ptr);
p = inPred(ptr);

If Node to be deleted has left subtree, then after deletion right thread of its predecessor should point to its successor. 

p->right = s;

Before deletion 15 is predecessor and 2 is successor of 16. After deletion of 16, the Node 20 becomes the successor of 15, so right thread of 15 will point to 20. 
If Node to be deleted has right subtree, then after deletion left thread of its successor should point to its predecessor. 

s->left = p;

Before deletion of 25 is predecessor and 34 is successor of 30. After deletion of 30, the Node 25 becomes the predecessor of 34, so left thread of 34 will point to 25. 

C++




// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
struct Node* caseB(struct Node* root, struct Node* par,
                   struct Node* ptr)
{
    struct Node* child;
 
    // Initialize child Node to be deleted has
    // left child.
    if (ptr->lthread == false)
        child = ptr->left;
 
    // Node to be deleted has right child.
    else
        child = ptr->right;
 
    // Node to be deleted is root Node.
    if (par == NULL)
        root = child;
 
    // Node is left child of its parent.
    else if (ptr == par->left)
        par->left = child;
    else
        par->right = child;
 
    // Find successor and predecessor
    Node* s = inSucc(ptr);
    Node* p = inPred(ptr);
 
    // If ptr has left subtree.
    if (ptr->lthread == false)
        p->right = s;
 
    // If ptr has right subtree.
    else {
        if (ptr->rthread == false)
            s->left = p;
    }
 
    free(ptr);
    return root;
}


Java




// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
static Node caseB(Node root, Node par,
                   Node ptr)
{
    Node child;
 
    // Initialize child Node to be deleted has
    // left child.
    if (ptr.lthread == false)
        child = ptr.left;
 
    // Node to be deleted has right child.
    else
        child = ptr.right;
 
    // Node to be deleted is root Node.
    if (par == null)
        root = child;
 
    // Node is left child of its parent.
    else if (ptr == par.left)
        par.left = child;
    else
        par.right = child;
 
    // Find successor and predecessor
    Node s = inSucc(ptr);
    Node p = inPred(ptr);
 
    // If ptr has left subtree.
    if (ptr.lthread == false)
        p.right = s;
 
    // If ptr has right subtree.
    else {
        if (ptr.rthread == false)
            s.left = p;
    }
    return root;
}
 
// This code is contributed by gauravrajput1


Python3




# Here 'par' is pointer to parent Node and 'ptr' is
# pointer to current Node.
def caseB(root, par, ptr):
    child = None;
 
    # Initialize child Node to be deleted has
    # left child.
    if (ptr.lthread == False):
        child = ptr.left;
 
    # Node to be deleted has right child.
    else:
        child = ptr.right;
 
    # Node to be deleted is root Node.
    if (par == None):
        root = child;
 
    # Node is left child of its parent.
    elif(ptr == par.left):
        par.left = child;
    else:
        par.right = child;
 
    # Find successor and predecessor
    s = inSucc(ptr);
    p = inPred(ptr);
 
    # If ptr has left subtree.
    if (ptr.lthread == False):
        p.right = s;
 
    # If ptr has right subtree.
    else:
        if (ptr.rthread == False):
            s.left = p;
     
    return root;
 
# This code is contributed by umadevi9616


C#




// Here 'par' is pointer to parent Node and
// 'ptr' is pointer to current Node.
static Node caseB(Node root, Node par,
                  Node ptr)
{
    Node child;
 
    // Initialize child Node to be deleted
    // has left child.
    if (ptr.lthread == false)
        child = ptr.left;
 
    // Node to be deleted has right child.
    else
        child = ptr.right;
 
    // Node to be deleted is root Node.
    if (par == null)
        root = child;
 
    // Node is left child of its parent.
    else if (ptr == par.left)
        par.left = child;
    else
        par.right = child;
 
    // Find successor and predecessor
    Node s = inSucc(ptr);
    Node p = inPred(ptr);
 
    // If ptr has left subtree.
    if (ptr.lthread == false)
        p.right = s;
 
    // If ptr has right subtree.
    else
    {
        if (ptr.rthread == false)
            s.left = p;
    }
    return root;
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
function caseB(root,par,ptr)
{
    let child;
  
    // Initialize child Node to be deleted has
    // left child.
    if (ptr.lthread == false)
        child = ptr.left;
  
    // Node to be deleted has right child.
    else
        child = ptr.right;
  
    // Node to be deleted is root Node.
    if (par == null)
        root = child;
  
    // Node is left child of its parent.
    else if (ptr == par.left)
        par.left = child;
    else
        par.right = child;
  
    // Find successor and predecessor
    let s = inSucc(ptr);
    let p = inPred(ptr);
  
    // If ptr has left subtree.
    if (ptr.lthread == false)
        p.right = s;
  
    // If ptr has right subtree.
    else {
        if (ptr.rthread == false)
            s.left = p;
    }
    return root;
}
 
 
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Case C: Node to be deleted has two children 

We find inorder successor of Node ptr (Node to be deleted) and then copy the information of this successor into Node ptr. After this inorder successor Node is deleted using either Case A or Case B. 

C++




// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
struct Node* caseC(struct Node* root, struct Node* par,
                   struct Node* ptr)
{
    // Find inorder successor and its parent.
    struct Node* parsucc = ptr;
    struct Node* succ = ptr->right;
 
    // Find leftmost child of successor
    while (succ->left != NULL) {
        parsucc = succ;
        succ = succ->left;
    }
 
    ptr->info = succ->info;
 
    if (succ->lthread == true && succ->rthread == true)
        root = caseA(root, parsucc, succ);
    else
        root = caseB(root, parsucc, succ);
 
    return root;
}


Java




// Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseC(Node root, Node par,
                      Node ptr)
    {
       
        // Find inorder successor and its parent.
        Node parsucc = ptr;
        Node succ = ptr.right;
 
        // Find leftmost child of successor
        while (succ.lthread == false) {
            parsucc = succ;
            succ = succ.left;
        }
 
        ptr.info = succ.info;
 
        if (succ.lthread == true && succ.rthread == true)
            root = caseA(root, parsucc, succ);
        else
            root = caseB(root, parsucc, succ);
 
        return root;
    }
 
// This code is contributed by umadevi9616


C#




// Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseC(Node root, Node par,
                      Node ptr)
    {
        // Find inorder successor and its parent.
        Node parsucc = ptr;
        Node succ = ptr.right;
 
        // Find leftmost child of successor
        while (succ.lthread == false) {
            parsucc = succ;
            succ = succ.left;
        }
 
        ptr.info = succ.info;
 
        if (succ.lthread == true && succ.rthread == true)
            root = caseA(root, parsucc, succ);
        else
            root = caseB(root, parsucc, succ);
 
        return root;
    }
 
// This code is contributed by umadevi9616


Javascript




<script>
 // Here 'par' is pointer to parent Node and 'ptr' is
      // pointer to current Node.
      function caseC(root, par, ptr)
      {
       
        // Find inorder successor and its parent.
        var parsucc = ptr;
        var succ = ptr.right;
 
        // Find leftmost child of successor
        while (succ.lthread == false) {
          parsucc = succ;
          succ = succ.left;
        }
 
        ptr.info = succ.info;
 
        if (succ.lthread == true && succ.rthread == true)
          root = caseA(root, parsucc, succ);
        else root = caseB(root, parsucc, succ);
 
        return root;
      }
       
      // This code is contributed by gauravrajput1
</script>


Python3




# Here 'par' is pointer to parent Node and 'ptr' is
# pointer to current Node.
def caseC(root, par, ptr):
   
    # Find inorder successor and its parent.
    parsucc = ptr;
    succ = ptr.right;
 
    # Find leftmost child of successor
    while (succ.lthread == False):
        parsucc = succ;
        succ = succ.left;
     
 
    ptr.info = succ.info;
 
    if (succ.lthread == True and succ.rthread == True):
        root = caseA(root, parsucc, succ);
    else:
        root = caseB(root, parsucc, succ);
 
    return root;
 
 
# This code contributed by umadevi9616


Below is Complete code: 

C++




// Complete C++ program to demonstrate deletion
// in threaded BST
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    struct Node *left, *right;
    int info;
 
    // false if left pointer points to predecessor
    // in Inorder Traversal
    bool lthread;
 
    // false if right pointer points to predecessor
    // in Inorder Traversal
    bool rthread;
};
 
// Insert a Node in Binary Threaded Tree
struct Node* insert(struct Node* root, int ikey)
{
    // Searching for a Node with given value
    Node* ptr = root;
    Node* par = NULL; // Parent of key to be inserted
    while (ptr != NULL) {
        // If key already exists, return
        if (ikey == (ptr->info)) {
            printf("Duplicate Key !\n");
            return root;
        }
 
        par = ptr; // Update parent pointer
 
        // Moving on left subtree.
        if (ikey < ptr->info) {
            if (ptr->lthread == false)
                ptr = ptr->left;
            else
                break;
        }
 
        // Moving on right subtree.
        else {
            if (ptr->rthread == false)
                ptr = ptr->right;
            else
                break;
        }
    }
 
    // Create a new Node
    Node* tmp = new Node;
    tmp->info = ikey;
    tmp->lthread = true;
    tmp->rthread = true;
 
    if (par == NULL) {
        root = tmp;
        tmp->left = NULL;
        tmp->right = NULL;
    }
    else if (ikey < (par->info)) {
        tmp->left = par->left;
        tmp->right = par;
        par->lthread = false;
        par->left = tmp;
    }
    else {
        tmp->left = par;
        tmp->right = par->right;
        par->rthread = false;
        par->right = tmp;
    }
 
    return root;
}
 
// Returns inorder successor using left
// and right children (Used in deletion)
struct Node* inSucc(struct Node* ptr)
{
    if (ptr->rthread == true)
        return ptr->right;
 
    ptr = ptr->right;
    while (ptr->lthread == false)
        ptr = ptr->left;
 
    return ptr;
}
 
// Returns inorder successor using rthread
// (Used in inorder)
struct Node* inorderSuccessor(struct Node* ptr)
{
    // If rthread is set, we can quickly find
    if (ptr->rthread == true)
        return ptr->right;
 
    // Else return leftmost child of right subtree
    ptr = ptr->right;
    while (ptr->lthread == false)
        ptr = ptr->left;
    return ptr;
}
 
// Printing the threaded tree
void inorder(struct Node* root)
{
    if (root == NULL)
        printf("Tree is empty");
 
    // Reach leftmost Node
    struct Node* ptr = root;
    while (ptr->lthread == false)
        ptr = ptr->left;
 
    // One by one print successors
    while (ptr != NULL) {
        printf("%d ", ptr->info);
        ptr = inorderSuccessor(ptr);
    }
}
 
struct Node* inPred(struct Node* ptr)
{
    if (ptr->lthread == true)
        return ptr->left;
 
    ptr = ptr->left;
    while (ptr->rthread == false)
        ptr = ptr->right;
    return ptr;
}
 
// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
struct Node* caseA(struct Node* root, struct Node* par,
                   struct Node* ptr)
{
    // If Node to be deleted is root
    if (par == NULL)
        root = NULL;
 
    // If Node to be deleted is left
    // of its parent
    else if (ptr == par->left) {
        par->lthread = true;
        par->left = ptr->left;
    }
    else {
        par->rthread = true;
        par->right = ptr->right;
    }
 
    // Free memory and return new root
    free(ptr);
    return root;
}
 
// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
struct Node* caseB(struct Node* root, struct Node* par,
                   struct Node* ptr)
{
    struct Node* child;
 
    // Initialize child Node to be deleted has
    // left child.
    if (ptr->lthread == false)
        child = ptr->left;
 
    // Node to be deleted has right child.
    else
        child = ptr->right;
 
    // Node to be deleted is root Node.
    if (par == NULL)
        root = child;
 
    // Node is left child of its parent.
    else if (ptr == par->left)
        par->left = child;
    else
        par->right = child;
 
    // Find successor and predecessor
    Node* s = inSucc(ptr);
    Node* p = inPred(ptr);
 
    // If ptr has left subtree.
    if (ptr->lthread == false)
        p->right = s;
 
    // If ptr has right subtree.
    else {
        if (ptr->rthread == false)
            s->left = p;
    }
 
    free(ptr);
    return root;
}
 
// Here 'par' is pointer to parent Node and 'ptr' is
// pointer to current Node.
struct Node* caseC(struct Node* root, struct Node* par,
                   struct Node* ptr)
{
    // Find inorder successor and its parent.
    struct Node* parsucc = ptr;
    struct Node* succ = ptr->right;
 
    // Find leftmost child of successor
    while (succ->lthread==false) {
        parsucc = succ;
        succ = succ->left;
    }
 
    ptr->info = succ->info;
 
    if (succ->lthread == true && succ->rthread == true)
        root = caseA(root, parsucc, succ);
    else
        root = caseB(root, parsucc, succ);
 
    return root;
}
 
// Deletes a key from threaded BST with given root and
// returns new root of BST.
struct Node* delThreadedBST(struct Node* root, int dkey)
{
    // Initialize parent as NULL and ptrent
    // Node as root.
    struct Node *par = NULL, *ptr = root;
 
    // Set true if key is found
    int found = 0;
 
    // Search key in BST : find Node and its
    // parent.
    while (ptr != NULL) {
        if (dkey == ptr->info) {
            found = 1;
            break;
        }
        par = ptr;
        if (dkey < ptr->info) {
            if (ptr->lthread == false)
                ptr = ptr->left;
            else
                break;
        }
        else {
            if (ptr->rthread == false)
                ptr = ptr->right;
            else
                break;
        }
    }
 
    if (found == 0)
        printf("dkey not present in tree\n");
 
    // Two Children
    else if (ptr->lthread == false && ptr->rthread == false)
        root = caseC(root, par, ptr);
 
    // Only Left Child
    else if (ptr->lthread == false)
        root = caseB(root, par, ptr);
 
    // Only Right Child
    else if (ptr->rthread == false)
        root = caseB(root, par, ptr);
 
    // No child
    else
        root = caseA(root, par, ptr);
 
    return root;
}
 
// Driver Program
int main()
{
    struct Node* root = NULL;
 
    root = insert(root, 20);
    root = insert(root, 10);
    root = insert(root, 30);
    root = insert(root, 5);
    root = insert(root, 16);
    root = insert(root, 14);
    root = insert(root, 17);
    root = insert(root, 13);
 
    root = delThreadedBST(root, 20);
    inorder(root);
 
    return 0;
}


Java




// Complete Java program to demonstrate deletion
// in threaded BST
import java.util.*;
class solution {
 
    static class Node {
        Node left, right;
        int info;
 
        // True if left pointer points to predecessor
        // in Inorder Traversal
        boolean lthread;
 
        // True if right pointer points to predecessor
        // in Inorder Traversal
        boolean rthread;
    };
 
    // Insert a Node in Binary Threaded Tree
    static Node insert(Node root, int ikey)
    {
        // Searching for a Node with given value
        Node ptr = root;
        Node par = null; // Parent of key to be inserted
        while (ptr != null) {
            // If key already exists, return
            if (ikey == (ptr.info)) {
                System.out.printf("Duplicate Key !\n");
                return root;
            }
 
            par = ptr; // Update parent pointer
 
            // Moving on left subtree.
            if (ikey < ptr.info) {
                if (ptr.lthread == false)
                    ptr = ptr.left;
                else
                    break;
            }
 
            // Moving on right subtree.
            else {
                if (ptr.rthread == false)
                    ptr = ptr.right;
                else
                    break;
            }
        }
 
        // Create a new Node
        Node tmp = new Node();
        tmp.info = ikey;
        tmp.lthread = true;
        tmp.rthread = true;
 
        if (par == null) {
            root = tmp;
            tmp.left = null;
            tmp.right = null;
        }
        else if (ikey < (par.info)) {
            tmp.left = par.left;
            tmp.right = par;
            par.lthread = false;
            par.left = tmp;
        }
        else {
            tmp.left = par;
            tmp.right = par.right;
            par.rthread = false;
            par.right = tmp;
        }
 
        return root;
    }
 
    // Returns inorder successor using left
    // and right children (Used in deletion)
    static Node inSucc(Node ptr)
    {
        if (ptr.rthread == true)
            return ptr.right;
 
        ptr = ptr.right;
        while (ptr.lthread == false)
            ptr = ptr.left;
 
        return ptr;
    }
 
    // Returns inorder successor using rthread
    // (Used in inorder)
    static Node inorderSuccessor(Node ptr)
    {
        // If rthread is set, we can quickly find
        if (ptr.rthread == true)
            return ptr.right;
 
        // Else return leftmost child of right subtree
        ptr = ptr.right;
        while (ptr.lthread == false)
            ptr = ptr.left;
        return ptr;
    }
 
    // Printing the threaded tree
    static void inorder(Node root)
    {
        if (root == null)
            System.out.printf("Tree is empty");
 
        // Reach leftmost Node
        Node ptr = root;
        while (ptr.lthread == false)
            ptr = ptr.left;
 
        // One by one print successors
        while (ptr != null) {
            System.out.printf("%d ", ptr.info);
            ptr = inorderSuccessor(ptr);
        }
    }
 
    static Node inPred(Node ptr)
    {
        if (ptr.lthread == true)
            return ptr.left;
 
        ptr = ptr.left;
        while (ptr.rthread == false)
            ptr = ptr.right;
        return ptr;
      
    }
 
    // Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseA(Node root, Node par,
                      Node ptr)
    {
        // If Node to be deleted is root
        if (par == null)
            root = null;
 
        // If Node to be deleted is left
        // of its parent
        else if (ptr == par.left) {
            par.lthread = true;
            par.left = ptr.left;
        }
        else {
            par.rthread = true;
            par.right = ptr.right;
        }
 
        return root;
    }
 
    // Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseB(Node root, Node par,
                      Node ptr)
    {
        Node child;
 
        // Initialize child Node to be deleted has
        // left child.
        if (ptr.lthread == false)
            child = ptr.left;
 
        // Node to be deleted has right child.
        else
            child = ptr.right;
 
        // Node to be deleted is root Node.
        if (par == null)
            root = child;
 
        // Node is left child of its parent.
        else if (ptr == par.left)
            par.left = child;
        else
            par.right = child;
 
        // Find successor and predecessor
        Node s = inSucc(ptr);
        Node p = inPred(ptr);
 
        // If ptr has left subtree.
        if (ptr.lthread == false)
            p.right = s;
 
        // If ptr has right subtree.
        else {
            if (ptr.rthread == false)
                s.left = p;
        }
 
        return root;
    }
 
    // Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseC(Node root, Node par,
                      Node ptr)
    {
        // Find inorder successor and its parent.
        Node parsucc = ptr;
        Node succ = ptr.right;
 
        // Find leftmost child of successor
        while (succ.lthread == false) {
            parsucc = succ;
            succ = succ.left;
        }
 
        ptr.info = succ.info;
 
        if (succ.lthread == true && succ.rthread == true)
            root = caseA(root, parsucc, succ);
        else
            root = caseB(root, parsucc, succ);
 
        return root;
    }
 
    // Deletes a key from threaded BST with given root and
    // returns new root of BST.
    static Node delThreadedBST(Node root, int dkey)
    {
        // Initialize parent as null and ptrent
        // Node as root.
        Node par = null, ptr = root;
 
        // Set true if key is found
        int found = 0;
 
        // Search key in BST : find Node and its
        // parent.
        while (ptr != null) {
            if (dkey == ptr.info) {
                found = 1;
                break;
            }
            par = ptr;
            if (dkey < ptr.info) {
                if (ptr.lthread == false)
                    ptr = ptr.left;
                else
                    break;
            }
            else {
                if (ptr.rthread == false)
                    ptr = ptr.right;
                else
                    break;
            }
        }
 
        if (found == 0)
            System.out.printf("dkey not present in tree\n");
 
        // Two Children
        else if (ptr.lthread == false && ptr.rthread == false)
            root = caseC(root, par, ptr);
 
        // Only Left Child
        else if (ptr.lthread == false)
            root = caseB(root, par, ptr);
 
        // Only Right Child
        else if (ptr.rthread == false)
            root = caseB(root, par, ptr);
 
        // No child
        else
            root = caseA(root, par, ptr);
 
        return root;
    }
 
    // Driver Program
    public static void main(String args[])
    {
        Node root = null;
 
        root = insert(root, 20);
        root = insert(root, 10);
        root = insert(root, 30);
        root = insert(root, 5);
        root = insert(root, 16);
        root = insert(root, 14);
        root = insert(root, 17);
        root = insert(root, 13);
 
        root = delThreadedBST(root, 20);
        inorder(root);
    }
}
// This code is contributed by Arnab Kundu


Python3




# Complete Python program to demonstrate deletion
# in threaded BST
 
class Node:
    def __init__(self):
        self.info = 0;
        self.left = None;
        self.right = None;
         
        # True if left pointer points to predecessor
        # in Inorder Traversal
        self.lthread = False;
         
        # True if right pointer points to predecessor
        # in Inorder Traversal
        self.rthread = False;
 
# Insert a Node in Binary Threaded Tree
def insert(root, ikey):
   
    # Searching for a Node with given value
    ptr = root;
    par = None; # Parent of key to be inserted
    while (ptr != None):
       
        # If key already exists, return
        if (ikey == (ptr.info)):
            print("Duplicate Key !");
            return root;
         
 
        par = ptr; # Update parent pointer
 
        # Moving on left subtree.
        if (ikey < ptr.info):
            if (ptr.lthread == False):
                ptr = ptr.left;
            else:
                break;
         
        # Moving on right subtree.
        else:
            if (ptr.rthread == False):
                ptr = ptr.right;
            else:
                break;
         
    # Create a new Node
    tmp = Node();
    tmp.info = ikey;
    tmp.lthread = True;
    tmp.rthread = True;
 
    if (par == None):
        root = tmp;
        tmp.left = None;
        tmp.right = None;
    elif(ikey < (par.info)):
        tmp.left = par.left;
        tmp.right = par;
        par.lthread = False;
        par.left = tmp;
    else:
        tmp.left = par;
        tmp.right = par.right;
        par.rthread = False;
        par.right = tmp;
     
    return root;
 
# Returns inorder successor using left
# and right children (Used in deletion)
def inSucc(ptr):
    if (ptr.rthread == True):
        return ptr.right;
 
    ptr = ptr.right;
    while (ptr.lthread == False):
        ptr = ptr.left;
 
    return ptr;
 
# Returns inorder successor using rthread
# (Used in inorder)
def inorderSuccessor(ptr):
   
    # If rthread is set, we can quickly find
    if (ptr.rthread == True):
        return ptr.right;
 
    # Else return leftmost child of right subtree
    ptr = ptr.right;
    while (ptr.lthread == False):
        ptr = ptr.left;
    return ptr;
 
# Printing the threaded tree
def inorder(root):
    if (root == None):
        print("Tree is empty");
 
    # Reach leftmost Node
    ptr = root;
    while (ptr.lthread == False):
        ptr = ptr.left;
 
    # One by one print successors
    while (ptr != None):
        print( ptr.info, end=" ");
        ptr = inorderSuccessor(ptr);
     
def inPred(ptr):
    if (ptr.lthread == True):
        return ptr.left;
 
    ptr = ptr.left;
    while (ptr.rthread == False):
        ptr = ptr.right;
    return ptr;
 
# Here 'par' is pointer to parent Node and 'ptr' is
# pointer to current Node.
def caseA(root, par, ptr):
   
    # If Node to be deleted is root
    if (par == None):
        root = None;
 
    # If Node to be deleted is left
    # of its parent
    elif(ptr == par.left):
        par.lthread = True;
        par.left = ptr.left;
    else:
        par.rthread = True;
        par.right = ptr.right;
     
    return root;
 
# Here 'par' is pointer to parent Node and 'ptr' is
# pointer to current Node.
def caseB(root, par, ptr):
    child;
 
    # Initialize child Node to be deleted has
    # left child.
    if (ptr.lthread == False):
        child = ptr.left;
 
    # Node to be deleted has right child.
    else:
        child = ptr.right;
 
    # Node to be deleted is root Node.
    if (par == None):
        root = child;
 
    # Node is left child of its parent.
    elif(ptr == par.left):
        par.left = child;
    else:
        par.right = child;
 
    # Find successor and predecessor
    s = inSucc(ptr);
    p = inPred(ptr);
 
    # If ptr has left subtree.
    if (ptr.lthread == False):
        p.right = s;
 
    # If ptr has right subtree.
    else:
        if (ptr.rthread == False):
            s.left = p;
    return root;
 
# Here 'par' is pointer to parent Node and 'ptr' is
# pointer to current Node.
def caseC(root, par, ptr):
   
    # Find inorder successor and its parent.
    parsucc = ptr;
    succ = ptr.right;
 
    # Find leftmost child of successor
    while (succ.lthread == False):
        parsucc = succ;
        succ = succ.left;
     
    ptr.info = succ.info;
 
    if (succ.lthread == True and succ.rthread == True):
        root = caseA(root, parsucc, succ);
    else:
        root = caseB(root, parsucc, succ);
 
    return root;
 
# Deletes a key from threaded BST with given root and
# returns new root of BST.
def delThreadedBST(root, dkey):
   
    # Initialize parent as None and ptrent
    # Node as root.
    par = None;
    ptr = root;
 
    # Set True if key is found
    found = 0;
 
    # Search key in BST : find Node and its
    # parent.
    while (ptr != None):
        if (dkey == ptr.info):
            found = 1;
            break;
         
        par = ptr;
        if (dkey < ptr.info):
            if (ptr.lthread == False):
                ptr = ptr.left;
            else:
                break;
        else:
            if (ptr.rthread == False):
                ptr = ptr.right;
            else:
                break;
         
    if (found == 0):
        print("dkey not present in tree");
 
    # Two Children
    elif(ptr.lthread == False and ptr.rthread == False):
        root = caseC(root, par, ptr);
 
    # Only Left Child
    elif(ptr.lthread == False):
        root = caseB(root, par, ptr);
 
    # Only Right Child
    elif(ptr.rthread == False):
        root = caseB(root, par, ptr);
 
    # No child
    else:
        root = caseA(root, par, ptr);
 
    return root;
 
# Driver Program
if __name__ == '__main__':
    root = None;
 
    root = insert(root, 20);
    root = insert(root, 10);
    root = insert(root, 30);
    root = insert(root, 5);
    root = insert(root, 16);
    root = insert(root, 14);
    root = insert(root, 17);
    root = insert(root, 13);
 
    root = delThreadedBST(root, 20);
    inorder(root);
 
# This code is contributed by Rajput-Ji


C#




// Complete C# program to demonstrate deletion
// in threaded BST
using System;
 
class GFG {
 
    public class Node {
        public Node left, right;
        public int info;
 
        // True if left pointer points to predecessor
        // in Inorder Traversal
        public bool lthread;
 
        // True if right pointer points to predecessor
        // in Inorder Traversal
        public bool rthread;
    };
 
    // Insert a Node in Binary Threaded Tree
    static Node insert(Node root, int ikey)
    {
        // Searching for a Node with given value
        Node ptr = root;
        Node par = null; // Parent of key to be inserted
        while (ptr != null) {
            // If key already exists, return
            if (ikey == (ptr.info)) {
                Console.Write("Duplicate Key !\n");
                return root;
            }
 
            par = ptr; // Update parent pointer
 
            // Moving on left subtree.
            if (ikey < ptr.info) {
                if (ptr.lthread == false)
                    ptr = ptr.left;
                else
                    break;
            }
 
            // Moving on right subtree.
            else {
                if (ptr.rthread == false)
                    ptr = ptr.right;
                else
                    break;
            }
        }
 
        // Create a new Node
        Node tmp = new Node();
        tmp.info = ikey;
        tmp.lthread = true;
        tmp.rthread = true;
 
        if (par == null) {
            root = tmp;
            tmp.left = null;
            tmp.right = null;
        }
        else if (ikey < (par.info)) {
            tmp.left = par.left;
            tmp.right = par;
            par.lthread = false;
            par.left = tmp;
        }
        else {
            tmp.left = par;
            tmp.right = par.right;
            par.rthread = false;
            par.right = tmp;
        }
 
        return root;
    }
 
    // Returns inorder successor using left
    // and right children (Used in deletion)
    static Node inSucc(Node ptr)
    {
        if (ptr.rthread == true)
            return ptr.right;
 
        ptr = ptr.right;
        while (ptr.lthread == false)
            ptr = ptr.left;
 
        return ptr;
    }
 
    // Returns inorder successor using rthread
    // (Used in inorder)
    static Node inorderSuccessor(Node ptr)
    {
        // If rthread is set, we can quickly find
        if (ptr.rthread == true)
            return ptr.right;
 
        // Else return leftmost child of right subtree
        ptr = ptr.right;
        while (ptr.lthread == false)
            ptr = ptr.left;
        return ptr;
    }
 
    // Printing the threaded tree
    static void inorder(Node root)
    {
        if (root == null)
            Console.Write("Tree is empty");
 
        // Reach leftmost Node
        Node ptr = root;
        while (ptr.lthread == false)
            ptr = ptr.left;
 
        // One by one print successors
        while (ptr != null) {
            Console.Write("{0} ", ptr.info);
            ptr = inorderSuccessor(ptr);
        }
    }
 
    static Node inPred(Node ptr)
    {
        if (ptr.lthread == true)
            return ptr.left;
 
        ptr = ptr.left;
        while (ptr.rthread == false)
            ptr = ptr.right;
        return ptr;
    }
 
    // Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseA(Node root, Node par,
                      Node ptr)
    {
        // If Node to be deleted is root
        if (par == null)
            root = null;
 
        // If Node to be deleted is left
        // of its parent
        else if (ptr == par.left) {
            par.lthread = true;
            par.left = ptr.left;
        }
        else {
            par.rthread = true;
            par.right = ptr.right;
        }
 
        return root;
    }
 
    // Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseB(Node root, Node par,
                      Node ptr)
    {
        Node child;
 
        // Initialize child Node to be deleted has
        // left child.
        if (ptr.lthread == false)
            child = ptr.left;
 
        // Node to be deleted has right child.
        else
            child = ptr.right;
 
        // Node to be deleted is root Node.
        if (par == null)
            root = child;
 
        // Node is left child of its parent.
        else if (ptr == par.left)
            par.left = child;
        else
            par.right = child;
 
        // Find successor and predecessor
        Node s = inSucc(ptr);
        Node p = inPred(ptr);
 
        // If ptr has left subtree.
        if (ptr.lthread == false)
            p.right = s;
 
        // If ptr has right subtree.
        else {
            if (ptr.rthread == false)
                s.left = p;
        }
 
        return root;
    }
 
    // Here 'par' is pointer to parent Node and 'ptr' is
    // pointer to current Node.
    static Node caseC(Node root, Node par,
                      Node ptr)
    {
        // Find inorder successor and its parent.
        Node parsucc = ptr;
        Node succ = ptr.right;
 
        // Find leftmost child of successor
        while (succ.lthread == false) {
            parsucc = succ;
            succ = succ.left;
        }
 
        ptr.info = succ.info;
 
        if (succ.lthread == true && succ.rthread == true)
            root = caseA(root, parsucc, succ);
        else
            root = caseB(root, parsucc, succ);
 
        return root;
    }
 
    // Deletes a key from threaded BST with given root and
    // returns new root of BST.
    static Node delThreadedBST(Node root, int dkey)
    {
        // Initialize parent as null and ptrent
        // Node as root.
        Node par = null, ptr = root;
 
        // Set true if key is found
        int found = 0;
 
        // Search key in BST : find Node and its
        // parent.
        while (ptr != null) {
            if (dkey == ptr.info) {
                found = 1;
                break;
            }
            par = ptr;
            if (dkey < ptr.info) {
                if (ptr.lthread == false)
                    ptr = ptr.left;
                else
                    break;
            }
            else {
                if (ptr.rthread == false)
                    ptr = ptr.right;
                else
                    break;
            }
        }
 
        if (found == 0)
            Console.Write("dkey not present in tree\n");
 
        // Two Children
        else if (ptr.lthread == false && ptr.rthread == false)
            root = caseC(root, par, ptr);
 
        // Only Left Child
        else if (ptr.lthread == false)
            root = caseB(root, par, ptr);
 
        // Only Right Child
        else if (ptr.rthread == false)
            root = caseB(root, par, ptr);
 
        // No child
        else
            root = caseA(root, par, ptr);
 
        return root;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        Node root = null;
 
        root = insert(root, 20);
        root = insert(root, 10);
        root = insert(root, 30);
        root = insert(root, 5);
        root = insert(root, 16);
        root = insert(root, 14);
        root = insert(root, 17);
        root = insert(root, 13);
 
        root = delThreadedBST(root, 20);
        inorder(root);
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
      // Complete JavaScript program to demonstrate deletion
      // in threaded BST
      class Node {
        constructor() {
          this.info = 0;
          // True if left pointer points to predecessor
          // in Inorder Traversal
          this.lthread = false;
          // True if right pointer points to predecessor
          // in Inorder Traversal
          this.rthread = false;
          this.left = null;
          this.right = null;
        }
      }
 
      // Insert a Node in Binary Threaded Tree
      function insert(root, ikey) {
        // Searching for a Node with given value
        var ptr = root;
        var par = null; // Parent of key to be inserted
        while (ptr != null) {
          // If key already exists, return
          if (ikey == ptr.info) {
            document.write("Duplicate Key !<br>");
            return root;
          }
 
          par = ptr; // Update parent pointer
 
          // Moving on left subtree.
          if (ikey < ptr.info) {
            if (ptr.lthread == false) ptr = ptr.left;
            else break;
          }
 
          // Moving on right subtree.
          else {
            if (ptr.rthread == false) ptr = ptr.right;
            else break;
          }
        }
 
        // Create a new Node
        var tmp = new Node();
        tmp.info = ikey;
        tmp.lthread = true;
        tmp.rthread = true;
 
        if (par == null) {
          root = tmp;
          tmp.left = null;
          tmp.right = null;
        } else if (ikey < par.info) {
          tmp.left = par.left;
          tmp.right = par;
          par.lthread = false;
          par.left = tmp;
        } else {
          tmp.left = par;
          tmp.right = par.right;
          par.rthread = false;
          par.right = tmp;
        }
 
        return root;
      }
 
      // Returns inorder successor using left
      // and right children (Used in deletion)
      function inSucc(ptr) {
        if (ptr.rthread == true) return ptr.right;
 
        ptr = ptr.right;
        while (ptr.lthread == false) ptr = ptr.left;
 
        return ptr;
      }
 
      // Returns inorder successor using rthread
      // (Used in inorder)
      function inorderSuccessor(ptr) {
        // If rthread is set, we can quickly find
        if (ptr.rthread == true) return ptr.right;
 
        // Else return leftmost child of right subtree
        ptr = ptr.right;
        while (ptr.lthread == false) ptr = ptr.left;
        return ptr;
      }
 
      // Printing the threaded tree
      function inorder(root) {
        if (root == null) document.write("Tree is empty");
 
        // Reach leftmost Node
        var ptr = root;
        while (ptr.lthread == false) ptr = ptr.left;
 
        // One by one print successors
        while (ptr != null) {
          document.write(ptr.info + " ");
          ptr = inorderSuccessor(ptr);
        }
      }
 
      function inPred(ptr) {
        if (ptr.lthread == true) return ptr.left;
 
        ptr = ptr.left;
        while (ptr.rthread == false) ptr = ptr.right;
        return ptr;
      }
 
      // Here 'par' is pointer to parent Node and 'ptr' is
      // pointer to current Node.
      function caseA(root, par, ptr) {
        // If Node to be deleted is root
        if (par == null) root = null;
        // If Node to be deleted is left
        // of its parent
        else if (ptr == par.left) {
          par.lthread = true;
          par.left = ptr.left;
        } else {
          par.rthread = true;
          par.right = ptr.right;
        }
 
        return root;
      }
 
      // Here 'par' is pointer to parent Node and 'ptr' is
      // pointer to current Node.
      function caseB(root, par, ptr) {
        var child;
 
        // Initialize child Node to be deleted has
        // left child.
        if (ptr.lthread == false) child = ptr.left;
        // Node to be deleted has right child.
        else child = ptr.right;
 
        // Node to be deleted is root Node.
        if (par == null) root = child;
        // Node is left child of its parent.
        else if (ptr == par.left) par.left = child;
        else par.right = child;
 
        // Find successor and predecessor
        var s = inSucc(ptr);
        var p = inPred(ptr);
 
        // If ptr has left subtree.
        if (ptr.lthread == false) p.right = s;
        // If ptr has right subtree.
        else {
          if (ptr.rthread == false) s.left = p;
        }
 
        return root;
      }
 
      // Here 'par' is pointer to parent Node and 'ptr' is
      // pointer to current Node.
      function caseC(root, par, ptr) {
        // Find inorder successor and its parent.
        var parsucc = ptr;
        var succ = ptr.right;
 
        // Find leftmost child of successor
        while (succ.lthread == false) {
          parsucc = succ;
          succ = succ.left;
        }
 
        ptr.info = succ.info;
 
        if (succ.lthread == true && succ.rthread == true)
          root = caseA(root, parsucc, succ);
        else root = caseB(root, parsucc, succ);
 
        return root;
      }
 
      // Deletes a key from threaded BST with given root and
      // returns new root of BST.
      function delThreadedBST(root, dkey) {
        // Initialize parent as null and ptrent
        // Node as root.
        var par = null,
          ptr = root;
 
        // Set true if key is found
        var found = 0;
 
        // Search key in BST : find Node and its
        // parent.
        while (ptr != null) {
          if (dkey == ptr.info) {
            found = 1;
            break;
          }
          par = ptr;
          if (dkey < ptr.info) {
            if (ptr.lthread == false)
            ptr = ptr.left;
            else break;
          } else {
            if (ptr.rthread == false)
            ptr = ptr.right;
            else break;
          }
        }
 
        if (found == 0)
        document.write("dkey not present in tree<br>");
        // Two Children
        else if (ptr.lthread == false && ptr.rthread == false)
          root = caseC(root, par, ptr);
        // Only Left Child
        else if (ptr.lthread == false)
        root = caseB(root, par, ptr);
        // Only Right Child
        else if (ptr.rthread == false)
        root = caseB(root, par, ptr);
        // No child
        else root = caseA(root, par, ptr);
 
        return root;
      }
 
      // Driver code
      var root = null;
 
      root = insert(root, 20);
      root = insert(root, 10);
      root = insert(root, 30);
      root = insert(root, 5);
      root = insert(root, 16);
      root = insert(root, 14);
      root = insert(root, 17);
      root = insert(root, 13);
 
      root = delThreadedBST(root, 20);
      inorder(root);
       
</script>


Output

5 10 13 14 16 17 30 

Time Complexity: The time complexity of the operations are –
 

Operation Name Time Complexity
Insertion O(1)
Deletion O(1)

Auxiliary Space Complexity:  The auxiliary space complexity of every operation is O(1). As it doesn’t use recursion or stack 

 



Similar Reads

Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Double Threaded Binary Search Tree
Double Threaded Binary Search Tree: is a binary search tree in which the nodes are not every left NULL pointer points to its inorder predecessor and the right NULL pointer points to the inorder successor.The threads are also useful for fast accessing the ancestors of a node.  Double Threaded Binary Search Tree is one of the most used types of Advan
15+ min read
Deletion in Binary Search Tree (BST)
Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node.  Case 3. Delete a Node with Both Children in BST Deleting a node with b
10 min read
Reverse Morris traversal using Threaded Binary Tree
What is Morris traversal?Morris (InOrder) Traversal is a tree traversal algorithm that does not use recursion or stacks. This traversal creates links as descendants and outputs nodes using those links. Finally, undo the changes to restore the original tree.Given a binary tree, task is to do reverse inorder traversal using Morris Traversal. Prerequi
10 min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Threaded Binary Tree | Insertion
We have already discuss the Binary Threaded Binary Tree.Insertion in Binary threaded tree is similar to insertion in binary tree but we will have to adjust the threads after insertion of each element. C representation of Binary Threaded Node: struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Ino
13 min read
Threaded Binary Tree
Inorder traversal of a Binary tree can either be done using recursion or with the use of a auxiliary stack. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. A binary tree is made threaded by making all right child pointers that would normally be NULL point to the inorder successor
10 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
m-Way Search Tree | Set-2 | Insertion and Deletion
Insertion in an m-Way search tree: The insertion in an m-Way search tree is similar to binary trees but there should be no more than m-1 elements in a node. If the node is full then a child node will be created to insert the further elements. Let us see the example given below to insert an element in an m-Way search tree.Example: To insert a new el
15+ min read
Ternary Search Tree (Deletion)
In the SET 1 post on TST we have described how to insert and search a node in TST. In this article, we will discuss algorithm on how to delete a node from TST. During delete operation we delete the key in bottom-up manner using recursion. The following are possible cases when deleting a key from trie. Key may not be there in TST. Solution: Delete o
14 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
Deletion in a Binary Tree
Given a binary tree, delete a node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with the last element. Examples : Input : Delete 10 in below tree        10
10 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
2-3 Trees | (Search, Insert and Deletion)
In binary search trees we have seen the average-case time for operations like search/insert/delete is O(log N) and the worst-case time is O(N) where N is the number of nodes in the tree. Like other Trees include AVL trees, Red Black Tree, B tree, 2-3 Tree is also a height balanced tree. The time complexity of search/insert/delete is O(log N) . A 2-
4 min read
Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1. Examples: Input: K = 0, 5 / \ 3 6 Output: 3 \ 5 \ 6 Input: K = 1, 2 / \ 1 3 Output: 3 \ 2 \ 1 Approach: The key observation in the problem is that the first node of the skewed
10 min read
Flatten a Binary Search Tree to convert the tree into a wave list in place only
Given a Binary Search Tree consisting of N distinct nodes, the task is to flatten the given Binary Search Tree to convert the tree into a wave list. A wave list arr[0..n-1] is called a wave list if arr[0] &gt;= arr[1] &lt;= arr[2] &gt;= arr[3] &lt;= arr[4] &gt;= ... . Examples: Input: 1 / \ 0 10Output: 0 \ 10 \ 1 Input: 3 / \ 1 7 / \ / \ 0 2 5 10 O
12 min read
Find the minimum Sub-tree with target sum in a Binary search tree
Given a binary tree and a target, find the number of nodes in the minimum sub-tree with the given sum equal to the target which is also a binary search tree. Examples: Input: 13 / \ 5 23 / \ / \ N 17 N N / 16Target: 38Output: 3Explanation: 5, 17, 16 is the smallest subtree with length 3. Input: 7 / \ N 23 / \ 10 23 / \ / \ N 17 N NTarget: 73Output:
9 min read
Difference between Binary Search Tree and AVL Tree
Binary Search Tree:A binary Search Tree is a node-based binary tree data structure that has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key.The right subtree of a node contains only nodes with keys greater than the node’s key.The left and right subtree each must also be a binary search t
2 min read
Count the Number of Binary Search Trees present in a Binary Tree
Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node 5 is a BST 5 / \ 4 6 Another BST we have is rooted
10 min read
Minimize deletion of edges to convert Tree into a forest of size at most N/2
Given a tree with N nodes, numbered from 0 to N - 1, the task is to find the minimum number of deletion of edges, such that, the tree is converted into a forest where each tree in the forest can have size less than equal to ⌊N/2⌋. Examples: Input: N = 3, edges = [[0, 1], [0, 2]] 0 / \ 1 2Output: 2Explanation: The maximum size of each tree after rem
14 min read
Van Emde Boas Tree | Set 4 | Deletion
It is highly recommended to read the previous articles on Van Emde Boas Tree first. Procedure for Delete: Here we are assuming that the key is already present in the tree. First we check if only one key is present, then assign the maximum and minimum of the tree to null value to delete the key.Base Case: If the universe size of the tree is two then
15+ min read
Deletion in Red-Black Tree
Deletion in a red-black tree is a bit more complicated than insertion. When a node is to be deleted, it can either have no children, one child or two children. Here are the steps involved in deleting a node in a red-black tree:If the node to be deleted has no children, simply remove it and update the parent node.If the node to be deleted has only o
15+ min read
Deletion in K Dimensional Tree
We strongly recommend to refer below posts as a prerequisite of this.K Dimensional Tree | Set 1 (Search and Insert) K Dimensional Tree | Set 2 (Find Minimum)In this post delete is discussed. The operation is to delete a given point from K D Tree. Like Binary Search Tree Delete, we recursively traverse down and search for the point to be deleted. Be
15+ min read
Deletion in Splay Tree
It is recommended to refer following post as prerequisite of this post. Splay Tree | Set 1 (Search) Following are the different cases to delete a key k from splay tree. If Root is NULL: We simply return the root.Else Splay the given key k. If k is present, then it becomes the new root. If not present, then last accessed leaf node becomes the new ro
15+ min read