Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 20e23bd

Browse files
committed
binary search tree
1 parent 9646acb commit 20e23bd

File tree

1 file changed

+37
-34
lines changed

1 file changed

+37
-34
lines changed

‎advanced_algorithm/binary_search_tree.md

Lines changed: 37 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -12,44 +12,47 @@
1212
> 验证二叉搜索树
1313
1414
```c++
15-
struct Result {
16-
TreeNode *maxNode;
17-
TreeNode *minNode;
18-
bool isValidate;
15+
class Solution {
16+
public:
17+
struct Result {
18+
TreeNode *maxNode;
19+
TreeNode *minNode;
20+
bool isValidate;
1921

20-
Result(bool validate = true, TreeNode *max = nullptr, TreeNode *min = nullptr)
21-
: isValidate(validate), maxNode(max), minNode(min) {
22+
Result(bool validate = true, TreeNode *max = nullptr, TreeNode *min = nullptr)
23+
: isValidate(validate), maxNode(max), minNode(min) {
2224

25+
}
26+
};
27+
bool isValidBST(TreeNode *root) {
28+
if (!root) {
29+
return true;
30+
}
31+
return helper(root).isValidate;
32+
}
33+
34+
Result helper(TreeNode *root) {
35+
if (!root) {
36+
return {};
37+
}
38+
auto left = helper(root->left);
39+
auto right = helper(root->right);
40+
if (!(left.isValidate && right.isValidate)) {
41+
return {false};
42+
}
43+
if (left.maxNode && left.maxNode->val >= root->val) {
44+
return {false};
45+
}
46+
if (right.minNode && right.minNode->val <= root->val) {
47+
return {false};
48+
}
49+
return {
50+
true,
51+
right.maxNode ? right.maxNode : root,
52+
left.minNode ? left.minNode : root,
53+
};
2354
}
2455
};
25-
bool isValidBST(TreeNode *root) {
26-
if (!root) {
27-
return true;
28-
}
29-
return helper(root).isValidate;
30-
}
31-
32-
Result helper(TreeNode *root) {
33-
if (!root) {
34-
return {};
35-
}
36-
auto left = helper(root->left);
37-
auto right = helper(root->right);
38-
if (!(left.isValidate && right.isValidate)) {
39-
return {false};
40-
}
41-
if (left.maxNode && left.maxNode->val >= root->val) {
42-
return {false};
43-
}
44-
if (right.minNode && right.minNode->val <= root->val) {
45-
return {false};
46-
}
47-
return {
48-
true,
49-
right.maxNode ? right.maxNode : root,
50-
left.minNode ? left.minNode : root,
51-
};
52-
}
5356
```
5457
5558
[insert-into-a-binary-search-tree](https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /