Skip to content

Commit

Permalink
【98. 验证二叉搜索树】【C++】
Browse files Browse the repository at this point in the history
  • Loading branch information
dekunma authored and labuladong committed Nov 12, 2020
1 parent 513fac4 commit 372b92b
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion 数据结构系列/二叉搜索树操作集锦.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};
```

0 comments on commit 372b92b

Please sign in to comment.