98. 验证二叉搜索树[中等]

153 阅读1分钟

上篇文章 判断是否是平衡二叉树 ,这篇文章来看下是否是二叉搜索树。

假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。 注意,上面的定义,是 节点的 左子树 只包含小于当前节点的数。是左子树,而不是仅仅要求 左孩子 小于 当前节点。左子树的意思是:当前节点所有左边的节点都小于当前节点。

所以,下面的代码是错误的:

public boolean isValidBST(TreeNode root) {
  if (root == null) {
    return true;
  }
  int val = root.val;
  if (root.left != null && root.left.val >= val) {
    return false;
  }
  if (root.right != null && root.right.val <= val) {
    return false;
  }
  if (!isValidBST(root.left) || !isValidBst(root.right)) {
    return false;
  }
  return true;
}

上图的树满足程序代码,但是左子树的节点7却大于根节点6,不是二叉搜索树。

正确的解法:

public boolean isValidBST(TreeNode root) {
  return helper(root, null, null);
}
​
private boolean helper(TreeNode root, Integer lower, Integer upper) {
  if (root == null) {
    return true;
  }
  int val = root.val;
  if (lower != null && lower >= val) {
    return false;
  }
  if (upper != null && val >= upper) {
    return false;
  }
  if (!helper(root.left, lower, val) || !helper(root.right, val, upper)) {
    return false;
  }
  return true;
}

二叉搜索树有一个特点:二叉搜索树的中序遍历是个单调递增的序列。也就是前面访问的节点肯定比后面的小。因此,可以中序遍历判断下。

public boolean isValidBST(TreeNode root) {
  Stack<TreeNode> stack = new Stack<TreeNode>();
  double inOrder = -Double.MAX_VALUE;
  while (!stack.empty() || root != null) {
    while (root != null) {
      stack.push(root);
      root = root.left;
    }
    root = stack.pop();
    if (root.val <= inOrder) {
      return false;
    }
    inOrder = root.val;
    root = root.right;
  }
  return true;
}

硬广告

欢迎关注公众号:double6