LeetCode: Verify Preorder Sequence in Binary Search Tree Posted on February 13, 2018July 26, 2020 by braindenny Verify Preorder Sequence in Binary Search Tree Similar Problems: Verify Preorder Serialization of a Binary Tree CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #binarytree, #monotone 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? Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. // https://code.dennyzhang.com/verify-preorder-sequence-in-binary-search-tree // Basic Ideas: monotonic stack // // pre-order: // push left sub-tree to stack // // M L R // // Inside stack: // // R // L // M // // When get right-subtree node, pop all left-subtree nodes.. // Complexity: Time O(n), Space O(n) func verifyPreorder(preorder []int) bool { stack := []int{} root := -1<<32 for _, v := range preorder { // right sub-tree is bigger than root if v < root { return false } for len(stack) > 0 && stack[len(stack)-1] < v { // pop root = stack[len(stack)-1] stack = stack[0:len(stack)-1] } stack = append(stack, v) } return true } Post Views: 4