There are 3 methods:
1. simply in order tranverse and get the ascending array, every next element is the successor of previous element.
2. It is Hawstein's method: There are 2 conditions:
1st: have right child, go find the left least grand child.
2nd don't. go up to find the closest ancestor.
Here is whole code:
// Ch4.4: Write an algorithm to find the ‘next’ node (i.e., in-order successor) of a given node in a binary search tree where each node has a link to its parent.
// based on Hawstein's solution
#include
#include
#include
using namespace std;
class BinNode{
public:
int key;
BinNode *parent, *lChild, *rChild;
BinNode(){}
BinNode(int t): key(t), parent(NULL), lChild(NULL), rChild(NULL){}
};
class BTree{
private:
BinNode *m_root;
public:
BTree(): m_root(NULL){}
BTree(BinNode *t): m_root(t){}
BinNode* getRoot() const{return m_root;}
BinNode* balanceTree(BinNode* pnode, BinNode *parent, int *arr, int low, int high){
if(low>high || arr == NULL)
return NULL;
int mid = (low+high)>>1;
pnode = new BinNode(arr[mid]);
pnode->parent = parent;
pnode->lChild = balanceTree(pnode->lChild, pnode, arr, low, mid-1);
pnode->rChild = balanceTree(pnode->rChild, pnode, arr, mid+1, high);
return pnode;
}
void PrintPre(BinNode *pnode)
{
if(pnode == NULL)
return;
cout << pnode->key << " ";
PrintPre(pnode->lChild);
PrintPre(pnode->rChild);
}
BinNode* minimal(BinNode* pnode){
if(pnode==NULL) return NULL;
while(pnode->lChild){
pnode = pnode->lChild;
}
return pnode;
}
BinNode* successor(BinNode* qnode){
if(qnode==NULL) return NULL;
if(qnode->rChild) return minimal(qnode->rChild);
BinNode *r = qnode->parent;
while(r && r->rChild==qnode){
qnode = r;
r = r->parent;
}
return r;
}
};
int main(){
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}; //{1, 2, 5, 7, 10, 13, 15, 21, 22};
int low = 0, high = sizeof(arr)/sizeof(int)-1;
cout <<"Balanced tree in array format\n";
BTree *bt = new BTree();
BinNode *proot = bt->balanceTree(bt->getRoot(), NULL, arr, low, high);
bt = new BTree(proot);
bt->PrintPre(bt->getRoot());
cout << "pnode is: "<< proot->key<
successor(proot))->key<
In order to verify, need to be careful, it is based on BST. So every simulation should have a BST structure. Random Tree will fail in this method.