【98. 验证二叉搜索树】【C++】

This commit is contained in:
dekunma
2020-11-11 14:21:23 +08:00
committed by labuladong
parent 513fac4f4b
commit 372b92bf7c

View File

@ -310,4 +310,36 @@ void BST(TreeNode root, int target) {
<img src="../pictures/qrcode.jpg" width=200 >
</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);
}
};
```