LeetCode 0255. Verify Preorder Sequence in Binary Search Tree Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0255. Verify Preorder Sequence in Binary Search Tree

Description

Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 1 <= preorder.length <= 104
  • 1 <= preorder[i] <= 104
  • All the elements of preorder are unique.

 

Follow up: Could you do it using only constant space complexity?

Solutions

Solution 1

PythonJavaC++Go
class Solution: def verifyPreorder(self, preorder: List[int]) -> bool: stk = [] last = -inf for x in preorder: if x < last: return False while stk and stk[-1] < x: last = stk.pop() stk.append(x) return True(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !