Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

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
}
linkedin
github
slack

Post Views: 4
Posted in MediumTagged #binarytree, monotone

Post navigation

LeetCode: Shortest Distance from All Buildings
LeetCode: One Edit Distance

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.