![]() |
VOOZH | about |
Given Preorder traversal of a BST, check if each non-leaf node has only one child. Assume that the BST contains unique entries.
Examples :
Input: pre[] = {20, 10, 11, 13, 12}
Output: Yes
The given array represents following BST. In the following BST, every internal
node has exactly 1 child. Therefore, the output is true.
20
/
10
\
11
\
13
/
12
In Preorder traversal, descendants (or Preorder successors) of every node appear after the node. In the above example, 20 is the first node in preorder and all descendants of 20 appear after it. All descendants of 20 are smaller than it. For 10, all descendants are greater than it. In general, we can say, if all internal nodes have only one child in a BST, then all the descendants of every node are either smaller or larger than the node. The reason is simple, since the tree is BST and every node has only one child, all descendants of a node will either be on left side or right side, means all descendants will either be smaller or greater.
Approach 1 (Naive):
This approach simply follows the above idea that all values on right side are either smaller or larger. Use two loops, the outer loop picks an element one by one, starting from the leftmost element. The inner loop checks if all elements on the right side of the picked element are either smaller or greater. The time complexity of this method will be O(n^2).
Approach 2:
Since all the descendants of a node must either be larger or smaller than the node. We can do the following for every node in a loop.
Below is the implementation of the above approach:
Yes
Time Complexity: O(n), where n is the length of the given pre[] array.
Auxiliary Space: O(1)
Approach 3 :
Below is the implementation of the above approach:
Yes
Time Complexity: O(n), where n is the length of the given pre[] array.
Auxiliary Space: O(1)
Approach 4:
Yes
Time complexity: O(n)
Auxiliary Space: O(n)