[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree_Medium tag: Preorder Traversal, tree

时间:2023-03-09 19:20:54
[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree_Medium tag: Preorder Traversal, tree

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 1:

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

Example 2:

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

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

这个题目的思路就用C++ easy to understand solution with thought process and detailed explanation, 因为每次看到preorder[i] > preorder[i-1] 表明有一个node的left tree结束了, 要找到那个node, 然后作为lower bound, i后面的元素应该都比lower bound要大.

T: O(n)    S: O(n)

class Solution:

    def verifyPreorder(self, preorder):
stack, low = [], None
for each in preorder:
if low != None and each < low:
return False
while stack and each > stack[-1]:
low = stack.pop()
stack.append(each)
return True