美文网首页
255. Verify Preorder Sequence in

255. Verify Preorder Sequence in

作者: jluemmmm | 来源:发表于2021-11-19 11:02 被阅读0次

    验证前序遍历的二叉树是否是 BST

    • Runtime: 84 ms, faster than 64.71%
    • Memory Usage: 43.4 MB, less than 17.65%
    • 时间复杂度O(n),空间复杂度O(n)

    维护一个栈用来获取每次的根节点,遍历比较左,弹出用来比较右边

    /**
     * @param {number[]} preorder
     * @return {boolean}
     */
    var verifyPreorder = function(preorder) {
      let root = Number.MIN_SAFE_INTEGER;
      const stack = [];
      for (let item of preorder) {
        if (item < root) {
          return false;
        }
        let len = stack.length;
        while (len > 0 && stack[len - 1] < item) {
          root = stack.pop();
          len = stack.length;
        }
        stack.push(item);
      }
      return true;
    };
    

    相关文章

      网友评论

          本文标题:255. Verify Preorder Sequence in

          本文链接:https://www.haomeiwen.com/subject/ccmstrtx.html