Skip to content

Commit 5cdf1e1

Browse files
committed
[7th batch] week 2 - validate binary search tree
1 parent 5cff581 commit 5cdf1e1

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

validate-binary-search-tree/liza0525.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,31 @@ def inorder_tree(tree_node):
2020
return False
2121

2222
return True
23+
24+
25+
# 7기 풀이
26+
# 시간 복잡도: O(n)
27+
# - 전체 트리 노드를 탐색하기 때문에 n
28+
# 공간 복잡도: O(n)
29+
# - 노드를 저장하는 리스트는 n의 길이만큼 생김
30+
class Solution:
31+
# 중위 순회 결과가 strictly increasing인지 확인하는 방식
32+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
33+
tree_res = []
34+
35+
def inorder_search(node):
36+
if node.left:
37+
inorder_search(node.left)
38+
39+
tree_res.append(node.val)
40+
41+
if node.right:
42+
inorder_search(node.right)
43+
44+
inorder_search(root)
45+
46+
for i in range(len(tree_res) - 1):
47+
# i번째 값이 i + 1번째 값보다 크거나 같으면 strictly increasing하지 않다는 의미이므로 False를 리턴한다.
48+
if tree_res[i] >= tree_res[i + 1]:
49+
return False
50+
return True

0 commit comments

Comments
 (0)