• 255.Verify Preorder Sequence in Binary Search Tree


        /*
         * 255.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. 
         * 11.21 By Mingyang
         * Time complexity O(n^2), space complexity O(1). 
         */
          public boolean verifyPreorder(int[] preorder) {
                if (preorder == null || preorder.length <= 1) {
                    return true;
                }         
                return dfs(preorder, 0, preorder.length - 1);
            }     
            private boolean dfs(int[] preorder, int low, int hi) {
                if (low >= hi) {
                    return true;
                }      
                int root = preorder[low];
                int i = low + 1;
                while (i <= hi && preorder[i] < root) {
                    i++;
                }         
                int j = i;
                while (j <= hi && preorder[j] > root) {
                    j++;
                }        
                if (j <= hi) {
                    return false;
                }        
                return dfs(preorder, low + 1, i - 1) && dfs(preorder, i, hi);
            }
        /*
         * 自己的代码,写的几乎一模一样,很高兴!
         * 唯一没想到的就是if (start >= end)都应该返回true
         * 因为2,3两个数的情况时,最后一个return的返回,第一个就是start>end的情况,这应该返回true
         */
        public static boolean verifyPreorder(int[] preorder) {
            int len = preorder.length;
            if (preorder == null || len == 0)
                return true;
            return verifyHelper(preorder, 0, len - 1);
        }
        public static boolean verifyHelper(int[] preorder, int start, int end) {
            if (start >= end)
                return true;
            int val = preorder[start];
            int index = -1;
            for (int i = start + 1; i <= end; i++) {
                if (preorder[i] > val && index == -1) {
                    index = i;
                }
                if (preorder[i] < val && index != -1)
                    return false;
            }
            if (index != -1)
                return verifyHelper(preorder, start + 1, end);
            return verifyHelper(preorder, start + 1, index - 1) && verifyHelper(preorder, index, end);        
        }
  • 相关阅读:
    Xcode8 1 创建coreData的ManagedObject后,报错 linker command failed with exit code 1
    在IOS中根据圆心坐标、半径和角度计算圆弧上的点坐标
    NodeJS学习目录
    nodeJS之URL
    nodeJS之域名DNS
    初识nodeJS
    使用nodeJS实现前端项目自动化之项目构建和文件合并
    nodeJS之fs文件系统
    nodeJS之二进制buffer对象
    nodeJS之进程process对象
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5603224.html
Copyright © 2020-2023  润新知