Question link
Idea: This
question mainly uses in-order traversal. Of course, as described in the previous question, there are several traversal methods. Only the recursive version is written here. In fact, you can also write a non-recursive version. Use a variable prev to save the last accessed value, and then judge it by comparing the conditions.
Code:
/**
* 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 {
public:
long long prev = LONG_MIN;
bool dfs(TreeNode* root){
if(root==NULL) return true;
if(dfs(root->left)==false) return false; //判断左子树
if(root->val <= prev) return false;
prev = root->val;
if(dfs(root->right)==false) return false; //判断右子树
else return true;
}
bool isValidBST(TreeNode* root) {
return dfs(root);
}
};