剑指 Offer 33. 二叉搜索树的后序遍历序列

43 阅读1分钟

剑指 Offer 33. 二叉搜索树的后序遍历序列

二叉树

  • 前序遍历 是 根 左 右
  • 中序遍历 是 左根右
  • 后续遍历 是 左右根

二叉搜索数概念如下图

image.png

思路 先看最大的左子树 和 最大的右子树 以及 根节点是否满足二叉搜索树的条件,不满足则直接跳出循环,否则递归判断 左右子树他们是否满足条件

const verifyPostorder = (postorder) => {
  const len = postorder.length;
  if (len <= 1) return true;
  // 后序遍历,最后一个是根节点,根节点可以划分 左子树  和 右子树
  const root = postorder[len - 1];
  // 找到第一个大于根节点的位置i
  let i = 0;
  while (postorder[i] < root) i++; 找出左右子树的理论临界小标
  // 从i开始,判断i右边到根节点之间的元素,是否都大于根节点值
  const res = postorder.slice(i, len - 1).every((x) => x > root);
  // res为false,说明存在一个右子树节点是大于根元素的,直接返回false
  // res为true,是基本符合后续遍历要求的,但是还得,继续判断剩下的左右子树
  return res
    ? verifyPostorder(postorder.slice(0, i)) &&
        verifyPostorder(postorder.slice(i, len - 1))
    : false;
};