1. 程式人生 > >[Swift]LeetCode255.驗證二叉搜索樹的先序序列 $ Verify Preorder Sequence in Binary Search Tree

[Swift]LeetCode255.驗證二叉搜索樹的先序序列 $ Verify Preorder Sequence in Binary Search Tree

pac solution lee int bsp UNC 驗證 num each

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.

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


給定一個數字數組,驗證它是否是二進制搜索樹的正確的預排序遍歷序列。

您可以假定序列中的每個數字都是唯一的。

進階:

你能只用恒定的空間復雜性來做嗎?


 1 class Solution {
 2     func verifyPreorder(_ preorder:[Int]) -> Bool{
 3         var preorder = preorder
 4         var low:Int = Int.min
 5         var i:Int = -1
 6         for a in preorder
 7         {
 8             if a < low
 9             {
10                 return false
11 } 12 while(i >= 0 && a > preorder[i]) 13 { 14 low = preorder[i] 15 i -= 1 16 } 17 i += 1 18 preorder[i] = a 19 } 20 return true 21 } 22 }

[Swift]LeetCode255.驗證二叉搜索樹的先序序列 $ Verify Preorder Sequence in Binary Search Tree