Skip to content

Commit 9412d3c

Browse files
committed
solve(w02): 98. Validate Binary Search Tree
1 parent c9460e4 commit 9412d3c

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# https://leetcode.com/problems/validate-binary-search-tree/
2+
3+
from typing import Optional
4+
import math
5+
6+
# Definition for a binary tree node.
7+
# class TreeNode:
8+
# def __init__(self, val=0, left=None, right=None):
9+
# self.val = val
10+
# self.left = left
11+
# self.right = right
12+
class Solution:
13+
def isValidBST1(self, root: Optional['TreeNode']) -> bool:
14+
"""
15+
[Complexity]
16+
- TC: O(n) (๋ชจ๋“  node ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธ)
17+
- SC: O(h) (recursion call stack) (balanced tree๋ผ๋ฉด O(logn), skewed tree๋ผ๋ฉด O(n))
18+
19+
[Approach]
20+
validํ•œ BST๋Š” ๋‹ค์Œ์„ ๋งŒ์กฑํ•ด์•ผ ํ•˜๋ฏ€๋กœ recursion์„ ์ด์šฉํ•ด์„œ ํ’€ ์ˆ˜ ์žˆ๋‹ค.
21+
1) left subtree๋Š” less than key
22+
2) right subtree๋Š” greater than key
23+
3) left & right subtree๋„ BST
24+
์ด๋•Œ, ๊ฐ subtree๋ฅผ recursive ํ•˜๊ฒŒ ํƒ€๊ณ  ๋“ค์–ด๊ฐ€์„œ ํ™•์ธํ•˜๋ ค๋ฉด, ๊ฐ ๋‹จ๊ณ„์—์„œ node, min floor val, max ceil val์ด ํ•„์š”ํ•˜๊ณ 
25+
๊ฐ ๋‹จ๊ณ„(= is_valid_subtree())๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ถ„๊ธฐ๋ฅผ ๋‚˜๋ˆ  ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค.
26+
1) node๊ฐ€ None์ผ ๋•Œ (base condition): True ๋ฐ˜ํ™˜
27+
2) ํ˜„์žฌ ๋…ธ๋“œ์˜ ๊ฐ’์ธ node.val์ด min floor ~ max ceil ๋ฒ”์œ„์— ํ•ด๋‹นํ•˜์ง€ ์•Š์„ ๋•Œ: False ๋ฐ˜ํ™˜
28+
3) ๊ทธ ์™ธ: left subtree์™€ right subtree๋„ valid ํ•œ์ง€ ์žฌ๊ท€์ ์œผ๋กœ ํ™•์ธ
29+
"""
30+
31+
def is_valid_subtree(node, floor, ceil):
32+
if not node:
33+
return True
34+
35+
if not (floor < node.val < ceil):
36+
return False
37+
38+
return is_valid_subtree(node.left, floor, node.val) and is_valid_subtree(node.right, node.val, ceil)
39+
40+
return is_valid_subtree(root, -math.inf, math.inf)
41+
42+
def isValidBST(self, root: Optional['TreeNode']) -> bool:
43+
"""
44+
[Complexity]
45+
- TC: O(n) (๋ชจ๋“  node ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธ)
46+
- SC: O(n) (recursion call stack O(h) + path O(n))
47+
48+
[Approach]
49+
inorder traversal ํ›„, ์›์†Œ๊ฐ€ ๋ชจ๋‘ ํ•ญ์ƒ strictly ascending sorted ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋ฉด ๋œ๋‹ค.
50+
"""
51+
52+
path = []
53+
is_asc = True
54+
55+
def inorder(node):
56+
nonlocal is_asc
57+
58+
if not node:
59+
return
60+
61+
inorder(node.left)
62+
63+
# path์— ์›์†Œ๊ฐ€ asc ์ •๋ ฌ๋˜์ง€ ์•Š์€ ์ฑ„๋กœ ๋“ค์–ด๊ฐ„๋‹ค๋ฉด, is_asc = False๋กœ ๋ณ€๊ฒฝ
64+
if path and path[-1] >= node.val:
65+
is_asc = False
66+
path.append(node.val)
67+
68+
inorder(node.right)
69+
70+
inorder(root)
71+
72+
return is_asc

0 commit comments

Comments
ย (0)