4.6 Design an algorithm to find the "next" node (also known as the middle order successor) of the specified node in the two-bit lookup tree. You can assume that each node contains a connection to the parent node.
Ideas:
There are two cases: 1) If there is a right subtree in the node, then the middle order successor is the smallest node in the right sub-tree.
2) If the node does not have a right subtree, then the successor is the first ancestor node on the left subtree of the given node at its ancestor nodes, so it always finds the parent, knowing that a parent node is found to make the node on the left subtree.
C + + Implementation code:
#include <iostream>#include<New>using namespacestd;structbinarysearchtree{intElem; Binarysearchtree*parent; Binarysearchtree*Left ; Binarysearchtree*Right ; Binarysearchtree (intx): Elem (x), parent (null), Left (null), right (null) {}};voidInsert (Binarysearchtree *&root,intz) {Binarysearchtree*y=NewBinarysearchtree (z); if(root==NULL) {Root=y; return; } Else if(root->left==null&&z<root->elem) {Root->left=y; Y->parent=Root; return; } Else if(root->right==null&&z>root->elem) {Root->right=y; Y->parent=Root; return; } if(z<root->elem) Insert (Root-left,z); ElseInsert (Root-right,z);}voidCreatebst (Binarysearchtree *&root) { intarr[Ten]= { in,4,6,1,8,3,0, +, at, the}; for(auto A:arr) insert (root,a);}voidInorder (Binarysearchtree *root) { if(Root) {inorder (root-Left ); cout<<root->elem<<" "; Inorder (Root-Right ); }}binarysearchtree* Findmin (Binarysearchtree *root) { if(root==null| |! Root->Left )returnRoot; while(root->Left ) {Root=root->Left ; } returnRoot;} Binarysearchtree* Findmax (Binarysearchtree *root) { if(root==null| |! Root->Right )returnRoot; while(root->Right ) {Root=root->Right ; } returnRoot;} Binarysearchtree* Findprocessor (Binarysearchtree *root,binarysearchtree*x) { if(x->Left )returnFindmax (x->Left ); Binarysearchtree*y=x->parent; while(y&&y->left==x) {x=y; Y=x->parent; } returny;} Binarysearchtree* Findsuccessor (Binarysearchtree *x) { if(x->Right )returnFindmin (x->Right ); Binarysearchtree*y=x->parent; while(y&&y->right==x) {x=y; Y=x->parent; } returny;}intMain () {Binarysearchtree*root=NULL; Createbst (root); Inorder (root);}
careercup-Tree and Figure 4.6