![]() |
VOOZH | about |
Given a binary tree and a node, the task is to find the inorder successor of this node. Inorder Successor of a node in the binary tree is the next node in the Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal.
In the below diagram, inorder successor of node 4 is 2, 1 is 3 and 5 is 1.
Table of Content
We do a reverse inorder traversal and keep track of the last visited node.
If we find the node and successor in the right subtree, we return it.
Below is the implementation of above approach:
2
We can optimize the auxiliary space used using Morris Traversal (A standard technique to do inorder traversal without stack and recursion)
Below is the implementation of the above approach:
2
We begin traversal from root. For every node, we need to take care of 3 cases for to find its inorder successor.
Please refer to Inorder Successor in Binary Search Tree for implementation.