mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-11 00:10:38 +08:00
【98. 验证二叉搜索树】【C++】
This commit is contained in:
@ -311,3 +311,35 @@ void BST(TreeNode root, int target) {
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
======其他语言代码======
|
======其他语言代码======
|
||||||
|
[dekunma](https://www.linkedin.com/in/dekun-ma-036a9b198/)提供第98题C++代码:
|
||||||
|
```C++
|
||||||
|
/**
|
||||||
|
* Definition for a binary tree node.
|
||||||
|
* struct TreeNode {
|
||||||
|
* int val;
|
||||||
|
* TreeNode *left;
|
||||||
|
* TreeNode *right;
|
||||||
|
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
|
||||||
|
* };
|
||||||
|
*/
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool isValidBST(TreeNode* root) {
|
||||||
|
// 用helper method求解
|
||||||
|
return isValidBST(root, nullptr, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isValidBST(TreeNode* root, TreeNode* min, TreeNode* max) {
|
||||||
|
// base case, root为nullptr
|
||||||
|
if (!root) return true;
|
||||||
|
|
||||||
|
// 不符合BST的条件
|
||||||
|
if (min && root->val <= min->val) return false;
|
||||||
|
if (max && root->val >= max->val) return false;
|
||||||
|
|
||||||
|
// 向左右子树分别递归求解
|
||||||
|
return isValidBST(root->left, min, root)
|
||||||
|
&& isValidBST(root->right, root, max);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
Reference in New Issue
Block a user