In the Binary Tree, the Inorder predecessor of a node is the previous node in the Inorder traversal of the Binary Tree. The Inorder Predecessor is NULL for the first node in Inorder traversal.
Example:
In the below diagram, inorder predecessor of node 7is 3 , node 2 is 7 and node 4 is null.
[Naive approach] Using Reverse Inorder - O(n) Time and O(h) Space
To find the inorder predecessor of a target node, we perform a reverse inorder traversal while keeping track of the last visited node. As we traverse, if we locate the target node, we check its left subtree for the predecessor; if found, we return it. If the current root's data matches the target, we return the last visited node from the left subtree as the predecessor. During each step, we update the last visited node and proceed to recursively explore the right subtree, continuing this process until we find the predecessor or complete the traversal.
Below is the implementation of the above approach:
Output
6
[Expected approach] Using Morris Traversal - O(n) Time and O(1) Space
We can optimize the auxiliary space of above approach used using Morris Traversal (A standard technique to do inorder traversal without stack and recursion).
Below is the implementation of the above approach: