leetcode第98题验证二叉搜索树

74 阅读1分钟

**题目: ** 给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

  • 节点的左子树只包含 小于 当前节点的数。
  • 节点的右子树只包含 大于 当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。 题目链接

我的JavaScript解法

  • 解法1:利用递归中序遍历二叉树,判断
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */

var isValidBST = function(root) {
  return help(root, null, null);
};

const help = (root, min, max) => {
  if (root === null) return true;
  if(min != null && root.val <= min) return false;
  if(max !=null && root.val >= max) return false;
  if(!help(root.left, min, root.val)) return false;
  if(!help(root.right, root.val, max)) return false;
  return true;
}
  • 解法2:利用栈中序遍历二叉树,判断
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */

var isValidBST = function(root) {
  if (root == null) return true;
  let pointer = root;
  let stack = [];
  let pre = -Infinity;
  while(stack.length > 0 || pointer != null) {
    if (pointer) {
      stack.push(pointer);
      pointer = pointer.left;
    } else {
      pointer = stack.pop();
      if(pre >= pointer.val) return false;
      pre = pointer.val;
      pointer = pointer.right;
    }
  }
  return true;
}

解析: 考察二叉搜索树的判断条件以及中序遍历二叉树

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)