Java Solution with Graph


  • 0
        public boolean verifyPreorder(int[] preorder) {
          int low = Integer.MIN_VALUE;
          Stack<Integer> stack = new Stack();
          for(int p : preorder){
            if(p < low) return false;
            while(!stack.isEmpty() && p > stack.peek()){
              low = stack.pop();    
            }
            stack.push(p);
          }    
          return true;
        }
    

    I cannot image the solution without drawing a real tree. In my case, it is a invalid BST, however the sequence can represented another valid BST.
    alt text


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.