Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement a function that returns the successor of a node in a binary search tre

ID: 3843658 • Letter: I

Question

Implement a function that returns the successor of a node in a binary search tree (the BST stores integer keys). A successor of a node n is defined as the smallest key x in the BST such that x is bigger than the value of n, or null if that does not exist. You may assume that the BST does not contain duplicate keys. The signature of the function you have to implement and the interface of the TreeNode class, which implements the BST, are given below. Note that getLeft(), getRight(), and getParent() return null if the node does not have a left, a right child, or is the root, respectively.

class TreeNode{

     int value;

     TreeNode *Left;        

     TreeNode *Right;

     TreeNode *Parent;                        

public:

   int getValue();

   TreeNode* getLeft();

   TreeNode* getRight();

   TreeNode* getParent();

   /* Returns -1 if no successor exists */

   int successor(TreeNode x) ;

}

Explanation / Answer

int successor(TreeNode x)

{

x= getRight(x);    /* in binary search tree always the right node is greater than the root node so if we want a                          successor of node x then we need to know right child value */

if(x!=null) //if node x has the right node the we return the value of that right node

return x->value;

else

return -1; // return -1 for no successor found

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote