vault backup: 2022-07-08 10:57:17
This commit is contained in:
parent
e18764d992
commit
2b8bae8a59
|
@ -60,9 +60,55 @@ A **valid BST** is defined as follows:
|
||||||
|
|
||||||
I have thought a lot of recursion methods, but at last I realized:
|
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.
|
> 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
|
### 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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in a new issue