LeetCode 98. 验证二叉搜索树

Posted by cody1991 on August 9, 2020

简单思路:深度优先的想法,去验证所有节点的左节点要小于当前节点的大小,以及当前节点的所有父节点的最小值。同理右节点

98. 验证二叉搜索树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function (root) {
  if (!root) return true;

  return dfs(root, -Infinity, Infinity);
};

function dfs(root, min, max) {
  if (!root) return true;

  if (root.val <= min || root.val >= max) return false;

  return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
}