Microsoft | Phone | Inorder successor

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2022-01-28Added By Anonymous
Source: Link

Root of the binary tree was given with an extra pointer pointing to it's parent as shown below and TreeNode is given as an input. Program should return it's next inorder successor.

1class TreeNode { 2 public int val; 3 public TreeNode left; 4 public TreeNode right; 5 public TreeNode parent; 6} 7 1 8 / \ 9 6 8 10 / \ / \ 11 2 3 10 4 12 13 14It's inorder traversal is [2,6,3,1,10,8,4]

input and output.

[2,6,3,1,10,8,4], 8 => 4

[5, 8, 9, 10], 9 => 10

[1,2,3,4,5], 5 => null.

Solution:

There are few cases that we need to cover to solve this problem.


Basic inorder traversal is to visit (left, root, right).

1.If the given node (n) has a right node then it is easy, traverse to the left most node in the right subtree. ( we got the answer).
2.If it doesn't have the right node this is where it gets tricky. we have to go up the tree using the parent node
3.if its parent nodes left node is equal to n, then found the answer.
4.If parents left node is not equals to n, keep traversing it's parent node by keeping track of it's previous parents.
1public TreeNode InOrderSuccessor(TreeNode node) { 2 if(node == null) return null; 3 // traverse left most node in the right subtree. 4 if(node.right != null) { 5 while(node.left != null) { 6 node = node.left; 7 } 8 return node; 9 } else { 10 TreeNode previous = node; 11 TreeNode current = node.parent; 12 while(current != null && current.left != previous) { 13 previous = current 14 current = current.parent; 15 } 16 return current; 17 } 18}

Solution Ref: CTCI

Comments