I need help in understanding this interview question:
Q: Find an algorithm to find the next node (e.g., inorder successor) of a given node in a binary search tree where each node has a link to its parent.
Does parent mean the in-order predecessor or just the immediate parent? How would one create a tree where the nodes have a link to the root node or inorder predecessor? Any help in understanding the data structure and the program below would be appreciated...
the solution (As posted in a form) is shown below:
public static TreeNode inorderSucc(TreeNode e) {
if (e != null) {
TreeNode p;
// Found right children -> return 1st inorder node on right
if (e.parent == null || e.right != null) {
p = leftMostChild(e.right);
} else {
// Go up until we’re on left instead of right (case 2b)
while ((p = e.parent) != null) {
if (p.left == e) {
break;
}
e = p;
}
}
return p;
}
return null;
}
public static TreeNode leftMostChild(TreeNode e) {
if (e == null) return null;
while (e.left != null) e = e.left;
return e;
}