前端算法学习-验证二叉搜索树

47 阅读1分钟

使用递归思想来验证二叉搜索树

什么是二叉搜索树

二叉搜索树,也被称为二叉排序树、有序二叉树、排序二叉树,是指一棵空树或具有以下性质的二叉树:

  1. 左子树上所有节点的值均小于它根节点的值
  2. 右子树上所有节点的值均大于它根节点的值
  3. 以此类推,左右子树也分别为二叉搜索树

题目分析

给定一个二叉树,判断其是否是一个有效的二叉搜索树

示例1:

输入:
    2
   / \
  1   3
输出: true

示例2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/va…


解题思路

根据二叉搜索树的特性可以得出:

  1. 当前节点的值是它左子树的最大值
  2. 当前节点的值是它右子树的最小值

构建二叉树结构

为了方便调试,先构建出树形结构

/**
 * 创建节点
 */
class Node {
  constructor (val) {
    this.val = val
    this.left = this.right = null
  }
}
/**
 * 构建树结构
 */
class treeNode {
  constructor() {
    this.root = null;
  }

  create(arr) {
    const rootVal = arr.shift();
    this.root = new Node(rootVal);
    const queue = [this.root];

    while (queue.length > 0) {
      const node = queue.shift();

      const leftVal = arr.shift();
      if (leftVal) {
        node.left = new Node(leftVal);
        queue.push(node.left);
      }

      const rightVal = arr.shift();
      if (rightVal) {
        node.right = new Node(rightVal);
        queue.push(node.right);
      }
    }
    return this.root;
  }
}

二叉搜索树验证逻辑

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
const isValidBST = function (root) {
    if (!root) return true
    const recursion = (root, min, max) => {
        if (root == null) return true
        if (min >= root.val || max <= root.val) {
            return false
        }
        return recursion(root.left, min, root.val) && recursion(root.right, root.val, max)
    }
    return recursion(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
}

运行结果

符合预期

const tree = new treeNode();
const root_1 = tree.create([2, 1, 3]);
const root_2 = tree.create([5, 1, 4, null, null, 3, 6]);

isValidBST(root_1); // true
isValidBST(root_2); // false