![]() |
VOOZH | about |
Given a preorder sequence of the binary search tree of N nodes. The task is to find its leftmost and rightmost nodes.
Examples:
Input : N = 5, preorder[]={ 3, 2, 1, 5, 4 }
Output : Leftmost = 1, Rightmost = 5
The BST constructed from this
preorder sequence would be:
3
/ \
2 5
/ /
1 4
Leftmost Node of this tree is equal to 1
Rightmost Node of this tree is equal to 5
Input : N = 3 preorder[]={ 2, 1, 3}
Output : Leftmost = 1, Rightmost = 3
Naive Approach:
Construct BST from the given preorder sequence. See this post for understanding the code to construct bst from a given preorder. After constructing the BST, find the leftmost and rightmost node by traversing from root to leftmost node and traversing from root to rightmost node.
Time Complexity: O(N)
Space Complexity: O(N)
Efficient Approach:
Instead of constructing the tree, make use of the property of BST. The leftmost node in BST always has the smallest value and the rightmost node in BST always has the largest value.
So, from the given array we just need to find the minimum value for the leftmost node and the maximum value for the rightmost node.
Below is the implementation of the above approach:
Leftmost node is 1 Rightmost node is 5
Time Complexity: O(N)
Space Complexity: O(1)