diff --git a/数据结构系列/二叉搜索树操作集锦.md b/数据结构系列/二叉搜索树操作集锦.md index 801b8fb..b30ceeb 100644 --- a/数据结构系列/二叉搜索树操作集锦.md +++ b/数据结构系列/二叉搜索树操作集锦.md @@ -310,4 +310,36 @@ void BST(TreeNode root, int target) {

-======其他语言代码====== \ 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); + } +}; +```