LeetCode Solutions

255. Verify Preorder Sequence in Binary Search Tree

Time: $O(n)$

Space: $O(h)$

			

class Solution {
 public:
  bool verifyPreorder(vector<int>& preorder) {
    int i = 0;
    dfs(preorder, i, INT_MIN, INT_MAX);
    return i == preorder.size();
  }

 private:
  void dfs(const vector<int>& preorder, int& i, int min, int max) {
    if (i == preorder.size())
      return;
    if (preorder[i] < min || preorder[i] > max)
      return;

    const int val = preorder[i++];
    dfs(preorder, i, min, val);
    dfs(preorder, i, val, max);
  }
};
			

class Solution {
  public boolean verifyPreorder(int[] preorder) {
    dfs(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
    return i == preorder.length;
  }

  private int i = 0;

  private void dfs(int[] preorder, int min, int max) {
    if (i == preorder.length)
      return;
    if (preorder[i] < min || preorder[i] > max)
      return;

    final int val = preorder[i++];
    dfs(preorder, min, val);
    dfs(preorder, val, max);
  }
}
			

class Solution:
  def verifyPreorder(self, preorder: List[int]) -> bool:
    i = 0

    def dfs(min: int, max: int) -> None:
      nonlocal i
      if i == len(preorder):
        return
      if preorder[i] < min or preorder[i] > max:
        return

      val = preorder[i]
      i += 1
      dfs(min, val)
      dfs(val, max)

    dfs(-math.inf, math.inf)
    return i == len(preorder)