Skip to content

Commit 9e2b07d

Browse files
committed
add solution : 98. Validate Binary Search Tree
1 parent 493745c commit 9e2b07d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
*
3+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
4+
* - ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ์˜ ํŠน์ง•(์™ผ์ชฝ ์ž์‹ ๋…ธ๋“œ < ๋ถ€๋ชจ ๋…ธ๋“œ < ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ)์„ ์ด์šฉํ•˜์—ฌ ๋ฌธ์ œ ํ’€๊ธฐ
5+
* - ๋ถ€๋ชจ ๋…ธ๋“œ ๊ฐ’, ์ตœ์ƒ์œ„ ๋ฃจํŠธ ๋…ธ๋“œ ๊ฐ’์„ ๋ชจ๋‘ ๊ณ ๋ คํ•ด์•ผ ํ•˜๋‹ˆ๊นŒ min, max๋กœ ๊ฐ’์˜ ๋ฒ”์œ„ ์ง€์ •ํ•˜๊ธฐ
6+
*
7+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n)
8+
* - n = root ํŠธ๋ฆฌ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
9+
* - ๋ชจ๋“  ๋…ธ๋“œ ํƒ์ƒ‰ : O(n)
10+
*
11+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(h)
12+
* - h = root ํŠธ๋ฆฌ ๋†’์ด
13+
* - ์žฌ๊ท€ ํ˜ธ์ถœ์ด ํŠธ๋ฆฌ ๋†’์ด๋งŒํผ ๋ฐœ์ƒํ•จ
14+
* - ์น˜์šฐ์นœ ํŠธ๋ฆฌ์˜ ๊ฒฝ์šฐ h = O(n)
15+
*
16+
*/
17+
function isValidBST(root: TreeNode | null): boolean {
18+
function helper(node: TreeNode | null, min: number, max: number): boolean {
19+
if (!node) return true;
20+
21+
if (node.val <= min || node.val >= max) return false;
22+
23+
return (
24+
helper(node.left, min, node.val) && helper(node.right, node.val, max)
25+
);
26+
}
27+
28+
return helper(root, -Infinity, Infinity);
29+
}

0 commit comments

Comments
ย (0)