-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate-binary-search-tree.js
55 lines (51 loc) · 1.1 KB
/
validate-binary-search-tree.js
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 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) {
// 中序遍历二叉搜索树等于遍历有序数组
// 空间复杂度 O(1)
let prev = null;
const inOrder = (node) => {
if (!node) {
return true;
}
const left = inOrder(node.left);
if (prev && prev.val >= node.val) {
return false;
}
// 记录前一个节点
prev = node;
const right = inOrder(node.right);
return left && right;
};
return inOrder(root);
// return inOrder2(root);
};
// 辅助数组
// 空间复杂度 O(n)
function inOrder2(root) {
const arr = [];
const dfs = (node) => {
if (node) {
dfs(node.left);
arr.push(node.val);
dfs(node.right);
}
};
dfs(root);
for (let i = 1; i < arr.length; i++) {
if (arr[i] <= arr[i - 1]) {
return false;
}
}
return true;
}