Skip to content

Commit 3dc6c7d

Browse files
committed
#251 validate-binary-search-tree solution
1 parent 9a1aa25 commit 3dc6c7d

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
풀이 :
3+
중위순회로 BST를 탐색하면 오름차순으로 탐색
4+
->중위순회 했을 떄 오름차순이 아니면 BST가 아니다
5+
현재 node의 val이 last_val보다 더 큰지 확인하면서 탐색한다
6+
7+
초기값은 INT_MIN이 있을경우를 생각해서 그보다 작은 값과 비교하기 위해 LONG_MIN사용
8+
9+
node 갯수 N
10+
11+
TC : O(N)
12+
노드 전체 순회
13+
14+
SC : O(N)
15+
재귀 호출스택이 N에 비례
16+
*/
17+
18+
#include <limits.h>
19+
20+
// Definition for a binary tree node.
21+
struct TreeNode {
22+
int val;
23+
TreeNode *left;
24+
TreeNode *right;
25+
TreeNode() : val(0), left(nullptr), right(nullptr) {}
26+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
27+
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
28+
};
29+
30+
class Solution {
31+
public:
32+
bool isValidBST(TreeNode* root) {
33+
long min = LONG_MIN;
34+
return dfs(root, &min);
35+
}
36+
37+
bool dfs(TreeNode* node, long* last_val){
38+
if (!node)
39+
return true;
40+
41+
if (!dfs(node->left, last_val))
42+
return false;
43+
44+
if (*last_val >= node->val)
45+
return false;
46+
*last_val = node->val;
47+
48+
if (!dfs(node->right, last_val))
49+
return false;
50+
51+
return true;
52+
}
53+
};

0 commit comments

Comments
 (0)