From 2b8bae8a591fc4ff8b82635b2923300f7262b479 Mon Sep 17 00:00:00 2001 From: juan Date: Fri, 8 Jul 2022 10:57:17 +0800 Subject: [PATCH] vault backup: 2022-07-08 10:57:17 --- .../Leetcode Validate-Binary-Search-Tree.md | 50 ++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md b/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md index f31faaf..d085390 100644 --- a/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md +++ b/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md @@ -60,9 +60,55 @@ A **valid BST** is defined as follows: I have thought a lot of recursion methods, but at last I realized: -> [!tip] The feature of +> [!tip] The feature of BST > For a BST, DFS inorder search returns an array of ascending numbers. -The +So, I use a DFS inorder, along with a prev reference pointer to keep track of previous value. to validate, the value of node should always be bigger than prev. + +See comment for why I use a **reference to pointer.** ### Solution + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} + * }; + */ +class Solution { + bool checker(TreeNode *root, int *&prev) { + // Use reference to pointer here, because the pointer address will change + // when assigning memory. Also can use pointer to pointer, or initialize the + // pointer and never change the address ever. + if (!root) { + return true; + } + if (!checker(root->left, prev)) { + return false; + } + if (prev && root->val <= *prev) { + return false; + } + if (!prev) { + // prev's address got changed + prev = new int; + } + *prev = root->val; + return checker(root->right, prev); + } + +public: + bool isValidBST(TreeNode *root) { + // DFS inorder traversal: valid BST returns a ascending array + int *prev = nullptr; + return checker(root, prev); + } +}; +``` \ No newline at end of file