From 372b92bf7cd5bbbb00c96717806bed7f254da655 Mon Sep 17 00:00:00 2001 From: dekunma <53892579+dekunma@users.noreply.github.com> Date: Wed, 11 Nov 2020 14:21:23 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=9098.=20=E9=AA=8C=E8=AF=81=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E3=80=91=E3=80=90C++?= =?UTF-8?q?=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../二叉搜索树操作集锦.md | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) 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); + } +}; +```