{x}
blog image

Verify Preorder Sequence in Binary Search Tree

Solution Explanation:

This problem asks whether a given array preorder represents a valid preorder traversal of a Binary Search Tree (BST). The key to solving this efficiently is understanding the properties of preorder traversal and BSTs.

Preorder Traversal: Preorder traversal visits the root node first, then recursively traverses the left subtree, and finally the right subtree.

Binary Search Tree (BST) Property: In a BST, all nodes in the left subtree of a node have values smaller than the node's value, and all nodes in the right subtree have values larger than the node's value.

Algorithm:

The solution uses a stack to simulate the preorder traversal and verify the BST property. The stack keeps track of nodes that haven't been "closed" yet (meaning their right subtree hasn't been processed).

  1. Initialization:

    • stk: An empty stack to store nodes.
    • last: A variable to keep track of the last processed node value. Initialized to negative infinity.
  2. Iteration: The code iterates through the preorder array.

  3. BST Property Check:

    • if x < last: If the current element x is less than last, it violates the BST property (a node is smaller than its ancestor). We immediately return false.
  4. Stack Manipulation:

    • while stk and stk[-1] < x: While the stack is not empty and the top element of the stack is less than the current element x, it means we've found a node in the left subtree that's smaller than the root of the current subtree (represented by x). We pop these smaller nodes from the stack, updating last to the popped node. This essentially simulates moving up the tree.
  5. Adding to Stack:

    • stk.append(x): Add the current element x to the stack.
  6. Final Check:

    • After iterating through the entire array, if the algorithm hasn't returned false, it means the preorder represents a valid BST. We return true.

Time Complexity Analysis:

The algorithm iterates through the preorder array once. Each element might be pushed onto and popped from the stack at most once. Therefore, the time complexity is O(N), where N is the length of the preorder array.

Space Complexity Analysis:

The space complexity is determined by the maximum size of the stack. In the worst case, the stack can hold all elements of the input array (e.g., a completely skewed tree). Therefore, the space complexity is O(N) in the worst case. However, in the best-case scenario (a balanced tree), the space complexity would be O(log N).