Skip to content

Commit f386b93

Browse files
committed
add solution: validate binary search tree
1 parent 4ef6503 commit f386b93

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

validate-binary-search-tree/flynn.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
풀이
3+
- BST의 속성을 이해한 후, 해당 속성을 검사하는 dfs 함수를 이용하면 풀이할 수 있습니다
4+
Big O
5+
- N: root 트리의 노드 개수
6+
- Time complexity: O(N)
7+
- 모든 노드에 대해 최대 1번의 탐색이 필요합니다
8+
- Space complexity: O(logN) (O(N) at worst)
9+
- check 함수의 재귀호출 스택 깊이는 트리의 높이에 비례하여 증가하므로 일반적으로 O(logN)의 공간복잡도를 가진다고 볼 수 있습니다
10+
하지만 트리가 심하게 치우친 경우 O(N)까지 커질 수 있습니다
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* type TreeNode struct {
16+
* Val int
17+
* Left *TreeNode
18+
* Right *TreeNode
19+
* }
20+
*/
21+
22+
const (
23+
MIN = -(2_147_483_648 + 1)
24+
MAX = 2_147_483_647 + 1
25+
)
26+
27+
func isValidBST(root *TreeNode) bool {
28+
return check(root.Left, MIN, root.Val) && check(root.Right, root.Val, MAX)
29+
}
30+
31+
/*
32+
helper dfs function
33+
*/
34+
35+
func check(node *TreeNode, min int, max int) bool {
36+
// base case
37+
if node == nil {
38+
return true
39+
}
40+
// node.val should be in the boundary (min, max)
41+
if !(min < node.Val && node.Val < max) {
42+
return false
43+
}
44+
// check for children nodes
45+
return check(node.Left, min, node.Val) && check(node.Right, node.Val, max)
46+
}

0 commit comments

Comments
 (0)