Skip to content

Commit 2df0e9e

Browse files
committed
validate-binary-search-tree solution
1 parent c00e5a3 commit 2df0e9e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
const dfs = (node, min, max) => {
15+
if (!node) {
16+
return true;
17+
}
18+
19+
if ((min !== undefined && node.val <= min) || (max !== undefined && node.val >= max)) {
20+
return false;
21+
}
22+
23+
return dfs(node.left, min, node.val) && dfs(node.right, node.val, max);
24+
};
25+
26+
return dfs(root, undefined, undefined);
27+
};
28+
29+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(n) -> ์ตœ์•…์˜ ๊ฒฝ์šฐ์ธ ์™„์ „ํ•œ ์ด์ง„ ํŠธ๋ฆฌ์˜ ๊ฒฝ์šฐ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•ด์„œ ํ™•์ธํ•ด์•ผ ํ•จ
30+
// ๊ณต๊ฐ„๋ณต์žก๋„ o(h) -> ์ตœ๋Œ€ ํŠธ๋ฆฌ์˜ ๋†’์ด๋งŒํผ ํ•จ์ˆ˜ํ˜ธ์ถœ ์Šคํƒ์— ํ•จ์ˆ˜์ปจํ…์ŠคํŠธ๊ฐ€ ์Œ“์ž„

0 commit comments

Comments
ย (0)