|
12 | 12 | > 验证二叉搜索树
|
13 | 13 |
|
14 | 14 | ```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; |
19 | 21 |
|
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) { |
22 | 24 |
|
| 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 | + }; |
23 | 54 | }
|
24 | 55 | };
|
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 | | -} |
53 | 56 | ```
|
54 | 57 |
|
55 | 58 | [insert-into-a-binary-search-tree](https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/)
|
|
0 commit comments