// =================== HAS PARENT POINTER ================================
// =======================================================================
// idea: if a node n has nonempty right subtree, return the leftmost node in the right subtree.
// if not, keep traversing parent till we find a node that is a left child of its parent. Then the parent is n's successor. If
// we reach the root, then n is the last node in inorder walk, and thus has no successor.
// very concise and elegant! Have parent pointer!
TreeNode *successor_in_binary_tree_with_parent(TreeNode *r) {
if(!r) return NULL;
if(r->right) {
TreeNode *p = r->right; // find leftmost node in r's right subtree
while(p->left) p = p->left;
return p;
}
while(r->parent && r->parent->right == r) // find the first parent whose left child contains r
r = r->parent;
return r->parent; // return NULL means r has no successor
}
// ========================== NO PARENT POINTER ==========================
// =======================================================================
// successor in BST without parent pointer!!!
// Note, BST!!!!
TreeNode* successor_in_BST_without_parent(TreeNode *root, TreeNode *n) {
if(!root || !n) return NULL;
if(n->right) {
TreeNode *p = n->right;
while(p->left) p = p->left;
return p;
}
TreeNode *cur = root, *p = NULL;
while(cur) {
if(n->val < cur->val) {
p = cur;
cur = cur->left;
}
else if(n->val > cur->val) {
p = cur;
cur = cur->right;
}
else break;
}
return p;
}
// ========================== NO PARENT POINTER ==========================
// =======================================================================
// find successor for general binary tree without parent!!!
// now that there is no parent, we can save a parent on fly! VERY ELEGANT!
// refer: http://algorithmsgeek.blogspot.com/2013/06/algo2-inorder-successor-in-binary-tree.html
Treenode* successor_in_BT_without_parent(TreeNode *root, TreeNode *parent, TreeNode *n) {
if(!root) return NULL;
if(root == n) {
if(root->right) {
TreeNode *p = root->right;
while(p->left) p = p->left;
return p;
}
else return parent; // gist!
}
else {
TreeNode *L = successor_in_BT_without_parent(root->left, root, n);
if(L) return L;
else return successor_in_BT_without_parent(root->right, root, n);
}
}
TreeNode* FUN(TreeNode *root, TreeNode *n) {
return successor_in_BT_without_parent(root, NULL, n);
}