LeetCode-98. Validate Binary Search Tree

问题描述

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Example :

img

1
2
3
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

解答

方法一:递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
* @Description: 98. Validate Binary Search Tree
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 方法一:递归
* @param {TreeNode} root
* @return {boolean}
*/
const isValidBST = function (root) {
const eventLoop = (cur, lower, upper) => {
if (!cur) {
return true
}
if (cur.val <= lower || cur.val >= upper) {
return false
}

return eventLoop(cur.left, lower, cur.val) && eventLoop(cur.right, cur.val, upper)
}

return eventLoop(root, -Infinity, Infinity)
}
方法二:非递归中序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @description: 方法二:非递归中序遍历
* @param {TreeNode} root
* @return {boolean}
*/
const isValidBST = function (root) {
let pre = -Infinity
let stack = []
let cur = root

while (cur || stack.length !== 0) {
if (cur) {
stack.push(cur)
cur = cur.left
} else {
cur = stack.pop()
if (cur.val <= pre) {
return false
}
pre= cur.val
cur = cur.right
}
}
return true
}