1

For an assignment for school, I need to take a binary search tree and convert it into a double-threaded binary search tree. I have a general understanding on how the threads work, but I realize that in order to know where it exactly the threads are, I need to know the parent of the last inserted node (prev), as well as the parent of that node as well (twoBack). However, in my attempts to modify one of the functions in order to save those values, I can not quite get what I am looking for.

If someone could point out exactly what I'm doing wrong, and explain it to me so that I can learn from my mistakes, I'd greatly appreciate it. Thanks!

Both of these functions a are part of the class for the BST itself:

void insert(const Key& k, const E& e) 
{
    root = inserthelp(root, k, e);
    nodecount++;
}
BSTNode<Key, E>* BST<Key, E>::inserthelp(BSTNode<Key, E>* root, const Key& k, const E& it) 
{
    if (root == NULL)  // Empty tree: create node
    {
        return new BSTNode<Key, E>(k, it, NULL, NULL);
    }
    if (k < root->key())
    {
        if (prev != NULL)
            twoBack = prev;
        prev = root;
        root->setLeft(inserthelp(root->left(), k, it));
    }
    else
    {
        if (prev != NULL)
            twoBack = prev;
        prev = root;            
        root->setRight(inserthelp(root->right(), k, it));
    }
    return root;       // Return tree with node inserted
}
Doug Blair
  • 23
  • 4
  • The largest node in the left subtree will always point to the root, which could be many levels up the tree. For example, in a balanced tree with 1 million nodes, there are 20 levels. If you try to add threads by saving the ancestors, you'd have to save all 20 ancestors. That's probably not a path you want to tread. – Jim Mischel Sep 30 '19 at 19:25
  • Two articles you might find interesting: https://www.geeksforgeeks.org/convert-binary-tree-threaded-binary-tree-2/ and https://www.geeksforgeeks.org/convert-binary-tree-threaded-binary-tree-set-2-efficient/. Note that these only cover right-threading. But left-threading is a fairly simple extension that you should be able to derive. – Jim Mischel Sep 30 '19 at 19:33
  • Thank you! This should help me enough to get unstuck! – Doug Blair Sep 30 '19 at 23:53

1 Answers1

0

This question ha sbeen aswered due to the comments left.

Doug Blair
  • 23
  • 4