Check if each internal node of a BST has exactly one child in Python

Suppose we have the preorder traversal of a binary search tree (BST). We have to check whether each internal node has only one child or not.

So, if the input is like preorder = [22, 12, 13, 15, 14], then the output will be True as BST is like −

22 12 13 15 14

Algorithm Approach

To solve this efficiently, we use the property that in a BST with single children, all descendants of a node are either smaller or larger. The algorithm works as follows −

  • Get the next preorder successor of the node

  • Get the last preorder successor of the node

  • When both successors are less than or greater than the current node, continue checking; otherwise return false

Step-by-Step Solution

We will follow these steps −

  • Initialize next := 0, last := 0
  • For i in range 0 to size of preorder - 1, do
    • next := preorder[i] - preorder[i+1]
    • last := preorder[i] - last value of preorder
    • If next * last < 0, then return False
  • Return True

Example

Let us see the implementation to get better understanding −

def solve(preorder):
    next_diff = 0
    last_diff = 0
    for i in range(len(preorder) - 1):
        next_diff = preorder[i] - preorder[i + 1]
        last_diff = preorder[i] - preorder[-1]
        if next_diff * last_diff < 0:
            return False
    return True

preorder = [22, 12, 13, 15, 14]
print(solve(preorder))

The output of the above code is −

True

How It Works

The algorithm checks if each node's immediate successor and the last node in preorder are on the same side (both smaller or both larger). If they are on different sides, it means the node has children on both sides, violating the single-child condition.

Example with Different Input

# Example that returns False
preorder_false = [8, 3, 5, 7, 6]
print(f"Input: {preorder_false}")
print(f"Result: {solve(preorder_false)}")

# Example that returns True
preorder_true = [20, 10, 11, 13, 12]
print(f"Input: {preorder_true}")
print(f"Result: {solve(preorder_true)}")
Input: [8, 3, 5, 7, 6]
Result: False
Input: [20, 10, 11, 13, 12]
Result: True

Conclusion

This algorithm efficiently determines if each internal node in a BST has exactly one child by comparing the signs of differences between each node and its immediate successor versus the last node. The time complexity is O(n) where n is the number of nodes.

Updated on: 2026-03-25T14:26:37+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements