Created
August 12, 2017 19:31
-
-
Save sdpatil/fb5d7dec1783e9dd6750f49a5abe539a to your computer and use it in GitHub Desktop.
Compute the successor
This file contains hidden or 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
| /** | |
| * Problem : FInd successor of a node in inorder traversal | |
| */ | |
| public class FindSuccessor { | |
| public BinaryTree<Integer> findSuccessor(BinaryTree<Integer> node) { | |
| BinaryTree<Integer> next = node; | |
| //If the node has a right child then go to right child and find the first node by following left children | |
| if (next.right != null) { | |
| next = next.right; | |
| while (next.left != null) | |
| next = next.left; | |
| return next; | |
| } | |
| //If the node does not have right child, then go up the parent chain till the node is not right child | |
| // of its parent | |
| while (next.parent != null && next.parent.right == next) | |
| next = next.parent; | |
| return next.parent; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment