255. Verify Preorder Sequence in

2021-11-19  本文已影响0人  jluemmmm

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

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

/**
 * @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;
};
上一篇下一篇

猜你喜欢

热点阅读