Skip to content

Commit 372b92b

Browse files
dekunmalabuladong
authored andcommitted
【98. 验证二叉搜索树】【C++】
1 parent 513fac4 commit 372b92b

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

数据结构系列/二叉搜索树操作集锦.md

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,4 +310,36 @@ void BST(TreeNode root, int target) {
310310
<img src="../pictures/qrcode.jpg" width=200 >
311311
</p>
312312

313-
======其他语言代码======
313+
======其他语言代码======
314+
[dekunma](https://www.linkedin.com/in/dekun-ma-036a9b198/)提供第98题C++代码:
315+
```C++
316+
/**
317+
* Definition for a binary tree node.
318+
* struct TreeNode {
319+
* int val;
320+
* TreeNode *left;
321+
* TreeNode *right;
322+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
323+
* };
324+
*/
325+
class Solution {
326+
public:
327+
bool isValidBST(TreeNode* root) {
328+
// 用helper method求解
329+
return isValidBST(root, nullptr, nullptr);
330+
}
331+
332+
bool isValidBST(TreeNode* root, TreeNode* min, TreeNode* max) {
333+
// base case, root为nullptr
334+
if (!root) return true;
335+
336+
// 不符合BST的条件
337+
if (min && root->val <= min->val) return false;
338+
if (max && root->val >= max->val) return false;
339+
340+
// 向左右子树分别递归求解
341+
return isValidBST(root->left, min, root)
342+
&& isValidBST(root->right, root, max);
343+
}
344+
};
345+
```

0 commit comments

Comments
 (0)