This is a fun little question that will give an interviewer the chance to gauge your understanding of Trees and BSTrees. If wanting more clarification check our binary TreeNode implementation and the wiki on Binary Search Tree.
So first of all to find the next highest node in a BSTree, you should think about clarifications and ambiguities as usual. There are 2 questions 2 mention:
- What are we supposed to return when our given node is the highest in the Tree?
- Do the nodes in our BSTree have a link to their parent?
For the purpose of this question we will assume that we are given clarifications to return null if our given node is the highest and to indeed have a link to our parent.
Finished with clarifications we will head into our algorithm. We have 2 cases we should look into.
How to find the next highest node in a BSTree
- Our node has a right child – In this case find the smallest node in that subtree
- Our node does not have a right child – In this case go upward to search for a parent whose value is bigger
To finish up we are going to provide a simple solution in Java to this question:
* @Author: Ajk Palikuqi
* @Question: How to find the next highest node in a BSTree
public class NextHighestTreeNode
public static TreeNode findNextHighestTreeNode(TreeNode root, TreeNode current)
if (current.getRight() != null)
private static TreeNode findSmallestNodeInTree(TreeNode root)
while (root.getLeft() != null)
root = root.getLeft();
private static TreeNode findBiggerParentNode(TreeNode root)
while (root.getParent() != null && root.getParent().getLeft() != root)
root = root.getParent();
As always you can find the full code in my GitHub Interview Questions repo.
Hope you guys enjoyed it… and I’ll see you guys next time ;D
Latest posts by Ajk (see all)
- Find Median from Numbers Array - January 1, 2018
- Find Whether a Number Can Be the Sum of Two Squares - August 12, 2017
- How to Find Two Primes Whose Sum is Equal to a Number N - April 22, 2017