Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit facf0f8

Browse files
committedMar 19, 2025ยท
solve: Validate Binary Search Tree
1 parent e4563b5 commit facf0f8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
 
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Constraints:
3+
- The number of nodes in the tree is in the range [1, 10^4].
4+
- -2^31 <= Node.val <= 2^31 - 1
5+
6+
Time Complexity: O(n)
7+
- ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•จ
8+
9+
Space Complexity: O(h)
10+
- ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์˜ ์ตœ๋Œ€ ๊นŠ์ด๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด
11+
12+
ํ’€์ด๋ฐฉ๋ฒ•:
13+
1. ๊ฐ ๋…ธ๋“œ๊ฐ€ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ ํ•œ์ •ํ•จ
14+
- root ๋…ธ๋“œ์˜ ๋ฒ”์œ„๋Š” (-๋ฌดํ•œ๋Œ€, +๋ฌดํ•œ๋Œ€)๋กœ ์„ค์ •
15+
2. Base case:
16+
- ๋นˆ ๋…ธ๋“œ์˜ ๊ฒฝ์šฐ True
17+
- ๋…ธ๋“œ ๊ฐ’์ด ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด False
18+
3. ์žฌ๊ท€๋ฅผ ํ™œ์šฉ:
19+
- ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ: max_val๋ฅผ ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธ (๋ชจ๋‘ ํ˜„์žฌ ๊ฐ’๋ณด๋‹ค ์ž‘์•„์•ผ ํ•จ)
20+
- ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ: min_val์„ ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธ (๋ชจ๋‘ ํ˜„์žฌ ๊ฐ’๋ณด๋‹ค ์ปค์•ผ ํ•จ)
21+
- ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ๋ชจ๋‘ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด BST
22+
"""
23+
# Definition for a binary tree node.
24+
# class TreeNode:
25+
# def __init__(self, val=0, left=None, right=None):
26+
# self.val = val
27+
# self.left = left
28+
# self.right = right
29+
class Solution:
30+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
31+
def validate(node, min_val, max_val):
32+
if not node:
33+
return True
34+
35+
if not (min_val < node.val < max_val):
36+
return False
37+
38+
return (validate(node.left, min_val, node.val) and
39+
validate(node.right, node.val, max_val))
40+
41+
return validate(root, float("-inf"), float("inf"))
42+

0 commit comments

Comments
 (0)
Please sign in to comment.