Last active
August 29, 2015 14:02
-
-
Save gabhi/09ed7c44357c69592cfc to your computer and use it in GitHub Desktop.
inorder successor in binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://www.youtube.com/watch?v=5cPbNCrdotA | |
//Function to find some data in the tree | |
Node* Find(Node*root, int data) { | |
if(root == NULL) return NULL; | |
else if(root->data == data) return root; | |
else if(root->data < data) return Find(root->right,data); | |
else return Find(root->left,data); | |
} | |
//Function to find Node with minimum value in a BST | |
struct Node* FindMin(struct Node* root) { | |
if(root == NULL) return NULL; | |
while(root->left != NULL) | |
root = root->left; | |
return root; | |
} | |
//Function to find Inorder Successor in a BST | |
struct Node* Getsuccessor(struct Node* root,int data) { | |
// Search the Node - O(h) | |
struct Node* current = Find(root,data); | |
if(current == NULL) return NULL; | |
if(current->right != NULL) { //Case 1: Node has right subtree | |
return FindMin(current->right); // O(h) | |
} | |
else { //Case 2: No right subtree - O(h) | |
struct Node* successor = NULL; | |
struct Node* ancestor = root; | |
while(ancestor != current) { | |
if(current->data < ancestor->data) { | |
successor = ancestor; // so far this is the deepest node for which current node is in left | |
ancestor = ancestor->left; | |
} | |
else | |
ancestor = ancestor->right; | |
} | |
return successor; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment