[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

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9357930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值