File tree Expand file tree Collapse file tree 1 file changed +33
-1
lines changed
Expand file tree Collapse file tree 1 file changed +33
-1
lines changed Original file line number Diff line number Diff 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+ ```
You can’t perform that action at this time.
0 commit comments