Skip to main content

Verify Preorder Sequence in Binary Search Tree

Description​

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.

You may assume each number in the sequence is unique.

Consider the following binary search tree:

     5
/ \
2 6
/ \
1 3

Example:​

Example 1:

Input: [5,2,6,1,3]
Output: false

Example 2:

Input: [5,2,1,3,6]
Output: true

Solution​

Approach​

  • Use a stack to simulate the traversal.
  • Maintain a variable low which represents the lowest value that the next node can take. Initially, set low to negative infinity.
  • Iterate through the array:
    • If we encounter a value less than low, it means the sequence is invalid.
    • If the current value is greater than the top of the stack, keep popping from the stack and update low to the value of the last popped element. This ensures that we are correctly moving to the right subtree.
    • Push the current value onto the stack.
function verifyPreorder(preorder) {
let stack = [];
let low = -Infinity;

for (let value of preorder) {
if (value < low) {
return false;
}
while (stack.length > 0 && value > stack[stack.length - 1]) {
low = stack.pop();
}
stack.push(value);
}
return true;
}

// Example usage:
const preorder1 = [5, 2, 6, 1, 3];
console.log(verifyPreorder(preorder1)); // Output: false

const preorder2 = [5, 2, 1, 3, 6];
console.log(verifyPreorder(preorder2)); // Output: true

Explanation:​

  1. Initialization:

    • A stack is used to keep track of the nodes.
    • low is initialized to -Infinity to represent the smallest possible value initially.
  2. Iteration:

    • For each value in the preorder array:
      • If the value is less than low, it means we are visiting a node in the right subtree that violates the BST property, hence return false.
      • If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update low to ensure that subsequent nodes in the right subtree are greater than this value.
      • Push the current value onto the stack.
  3. Return:

    • If we successfully iterate through the entire array without finding any violations, return true.

Complexity:​

  • Time Complexity: O(n), where n is the length of the preorder array. Each element is pushed and popped from the stack at most once.
  • Space Complexity: O(n), where n is the length of the preorder array, which is the worst-case space complexity for the stack.

References​

Author:

Loading...