Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • Valid preorder tree
  • 255. Verify Preorder BST
  • 331. Verify Preorder Serialization of a Binary Tree

Was this helpful?

  1. 6. Binary Tree

Valid Ordered Tree

Valid preorder tree

Given an ArrayList of Nodes, with each Node having an ID and a parent ID, determine whether the List is given in preorder.

  • parent set store the parentID

  • Except root node, general node's parentID will be traversed and stored in parent set.

    boolean isPreorder(Node[] nodes){
      Set<Integer> parents = new HashSet<>();
      for(int i=0; i<nodes.size(); i++){
        if(nodes[i].parents != null){
          if(parents.contains(nodes[i].parentID)){
            parents.add(nodes[i].id);
          }else{
            return false;
          }
        }else{
          parents.add(nodes[i].id);
        }
      }
      return true;
    }

255. Verify Preorder BST

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.

  • Use a stack to store the traversed left tree, if p smaller than last pushed number, then we still in the left tree. Otherwise, pop all the node in stack if we are in right tree. Take the last poped number as upper bound

public boolean verifyPreorder(int[] preorder) {
    Stack<Integer> s = new Stack<>();
    int low = Integer.MIN_VALUE;
    for(int n: preorder){
        if(n < low) return false;
        // if n in right tree
        while( !s.isEmpty() && n > s.peek()){
            low = s.pop();
        }
        s.push(n);
    }
    return true;
}

331. Verify Preorder Serialization of a Binary Tree

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #

  • using a stack, scan left to right

    • case 1: we see a number, just push it to the stack

    • case 2: we see #, check if the top of stack is also #, if so, pop #, pop the number in a while loop, until top of stack is not #

  • in the end, check if stack size is 1, and stack top is #

public boolean isValidSerialization(String preorder) {
    Stack<String> s = new Stack<>();
    for(String c: preorder.split(",")){
        while( c.equals("#") && !s.isEmpty() && s.peek().equals("#")){
            s.pop();
            if(s.isEmpty()) return false;
            s.pop();
        }
        s.push(c);
    }
    return s.size() == 1 && s.peek().equals("#");
}
PreviousTraverseNextConstruct Binary Tree

Last updated 5 years ago

Was this helpful?