zoukankan      html  css  js  c++  java
  • Leetcode 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?


    解题思路:

    参考答案,记住!

    Kinda simulate the traversal, keeping a stack of nodes (just their values) of which we're still in the left subtree. If the next number is smaller than the last stack value, then we're still in the left subtree of all stack nodes, so just push the new one onto the stack. But before that, pop all smaller ancestor values, as we must now be in their right subtrees (or even further, in the right subtree of an ancestor). Also, use the popped values as a lower bound, since being in their right subtree means we must never come across a smaller number anymore.


    Java code:

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

    Reference:

    1. https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space

  • 相关阅读:
    详说清除浮动
    ie7 z-index 失效问题
    ul里不能直接嵌套div(在ie7以前版本)
    jQuery 发送验证码倒计时按钮
    VBA: Cant find project or librar
    InstallShield Limited Edition制作安装文件
    InstallShield制作升级安装包
    VBA 获取Sheet最大行
    求两条线段交点zz
    VBA找不到progress bar的处理办法。
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4899725.html
Copyright © 2011-2022 走看看