Skip to content

Commit 338067f

Browse files
committed
Add solution for Validate Binary Search Tree
1 parent 0470660 commit 338067f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
# https://leetcode.com/problems/validate-binary-search-tree/description/
3+
# Intuition
4+
BST๋ฅผ ์ค‘์œ„ ์ˆœํšŒํ•˜๋ฉด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๊ฐ’์ด ์ •๋ ฌ๋œ๋‹ค๋Š” ์ ์— ์ฐฉ์•ˆํ–ˆ์Šต๋‹ˆ๋‹ค.
5+
6+
# Complexity
7+
- Time complexity: ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋ฅผ N์ด๋ผ๊ณ  ํ•  ๋•Œ, O(N)
8+
9+
- Space complexity: ์žฌ๊ท€๋กœ ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ํ˜ธ์ถœ ์Šคํƒ์ด ์Œ“์ด๋Š”๋ฐ
10+
ํŠธ๋ฆฌ์˜ ๋†’์ด๋ฅผ H๋ผ๊ณ  ํ•  ๋•Œ, ํ˜ธ์ถœ ์Šคํƒ์€ H ๋งŒํผ ์Œ“์ž…๋‹ˆ๋‹ค. => ๊ณต๊ฐ„ ๋ณต์žก๋„ O(H)
11+
"""
12+
13+
14+
class Solution:
15+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
16+
prev = [None]
17+
18+
def inorder(node):
19+
if not node:
20+
return True
21+
22+
if not inorder(node.left):
23+
return False
24+
25+
if prev[0] is not None and prev[0] >= node.val:
26+
return False
27+
prev[0] = node.val
28+
29+
return inorder(node.right)
30+
31+
return inorder(root)

0 commit comments

Comments
ย (0)