Leetcode 255: Verify Preorder Sequence in Binary Search 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.
Follow up:
Could you do it using only constant space complexity?
1 public class Solution { 2 public bool VerifyPreorder(int[] preorder) { 3 if (preorder == null || preorder.Length < 2) return true; 4 5 var stack = new Stack<int>(); 6 var low = Int32.MinValue; 7 8 for (int i = 0; i < preorder.Length; i++) 9 { 10 if (preorder[i] < low) return false; 11 12 while (stack.Count > 0 && preorder[i] > stack.Peek()) 13 { 14 low = stack.Pop(); 15 } 16 17 stack.Push(preorder[i]); 18 } 19 20 return true; 21 } 22 } 23 24 // time limit exceeded 25 public class Solution1 { 26 public bool VerifyPreorder(int[] preorder) { 27 if (preorder == null || preorder.Length < 2) return true; 28 29 return DFS(preorder, 0, preorder.Length - 1); 30 } 31 32 private bool DFS(int[] preorder, int start, int end) 33 { 34 if (start >= end) return true; 35 int right = start + 1; 36 37 while (right <= end) 38 { 39 if (preorder[right] > preorder[start]) 40 { 41 break; 42 } 43 44 right++; 45 } 46 47 for (int i = right + 1; i <= end; i++) 48 { 49 if (preorder[i] < preorder[start]) 50 { 51 return false; 52 } 53 } 54 55 return DFS(preorder, start + 1, right - 1) && DFS(preorder, right, end); 56 } 57 }

浙公网安备 33010602011771号