提交 372b92bf 编写于 作者: D dekunma 提交者: labuladong

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

上级 513fac4f
......@@ -310,4 +310,36 @@ void BST(TreeNode root, int target) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
[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);
}
};
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册