Problem
Given Preorder traversal of a BST, check if each non-leaf node has only one child. Assume that the BST contains unique entries.
Examples
Example 1
graph TD A(8) A --- B(3) A ~~~ N1:::hidden B --- C(2) B ~~~ N2:::hidden C ~~~ N3:::hidden C --- D(6) classDef hidden display:none
|
|
Example 2
graph TD A(8) A --- B(3) A ~~~ N1:::hidden B --- C(2) B --- D(6) classDef hidden display:none
|
|
Solution
This problem revolves around properties of a BST and its preorder traversal. In a BST:
- Nodes are visited in the order: root -> left subtree -> right subtree.
Now, if each - non-leaf node has only one child, then adjacencies in the array represent a path either entirely increasing (right children only) or entirely decreasing (left children only).
For e.g. for node 8, all the descendants are smaller than 8, as they all appear on left of 8. Similarly, for node 2, all its descendants are greater than 2, and they all appear on the right of 2.
This is because, in a BST with only one child per node, every descendant will lie on either the left or right subtree, leading to this consistent behaviour.
Method 1 - Naive
This approach is based on the idea that all values to the right of a node are either smaller or larger. It uses two loops: the outer loop iteratively selects each element starting from the leftmost, and the inner loop verifies whether all elements to the right of the selected element are either smaller or larger. The time complexity for this method is O(n^2)
.
Method 2 - Using BST property
You can verify this property by examining consecutive values in the preorder traversal and comparing each value to the last value in the list (acting as the maximum or minimum boundary).
Approach
- Compare Subsequent Nodes in Preorder Traversal:
- Traverse the adjacency pairs of the
preorder
list. - For each pair of nodes
preorder[i]
andpreorder[i+1]
, verify whether the value lies within the correct boundary (increasing or decreasing).
- Traverse the adjacency pairs of the
- Boundary Conditions:
- During traversal, maintain the minimum and maximum range observed.
- For non-leaf nodes, their only child will adjust the bounds accordingly.
- Output Determination:
- If all pairs satisfy the conditions for a single child, return
True
. - Otherwise, return
False
.
- If all pairs satisfy the conditions for a single child, return
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, since the algorithm traverses the preorder array once. - 🧺 Space complexity:
O(1)
. Only constant space is used for this comparison.