Skip to content

Commit b84cb92

Browse files
author
bhan
committed
validate binary search tree solution
1 parent 2c24c86 commit b84cb92

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {boolean}
12+
*/
13+
var isValidBST = function (root) {
14+
function helper(node, lower = -Infinity, upper = Infinity) {
15+
if (!node) return true;
16+
17+
const val = node.val;
18+
19+
// ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด false
20+
if (val <= lower || val >= upper) {
21+
return false;
22+
}
23+
24+
// ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ: ์ตœ์†Œ๊ฐ’์€ ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’
25+
if (!helper(node.right, val, upper)) {
26+
return false;
27+
}
28+
29+
// ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ: ์ตœ๋Œ€๊ฐ’์€ ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’
30+
if (!helper(node.left, lower, val)) {
31+
return false;
32+
}
33+
34+
return true;
35+
}
36+
37+
return helper(root);
38+
};

0 commit comments

Comments
ย (0)