[Naive Approach] Using In-order traversal - O(n) Time and O(h) Space
The idea is to traverse the binary tree in in-order manner and maintain the count of nodes visited so far. For each node, increment the count. If the count becomes equal to n, then return the value of current node. Otherwise, check left and right subtree of node. If nth node is not found in current tree, then return -1.
Below is the implementation of the above approach.
Output
10
[Expected Approach] Using Morris Traversal Algorithm - O(n) Time and O(1) Space
The idea is to use Morris Traversal Algorithm to perform in-order traversal of the binary tree, while maintaining the count of nodes visited so far.
Below is the implementation of the above approach: