Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 12, 2017 19:31
Show Gist options
  • Select an option

  • Save sdpatil/fb5d7dec1783e9dd6750f49a5abe539a to your computer and use it in GitHub Desktop.

Select an option

Save sdpatil/fb5d7dec1783e9dd6750f49a5abe539a to your computer and use it in GitHub Desktop.
Compute the successor
/**
* 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