用一个right记录正确与否,long int保存最小值,进行一轮中序遍历,每次比较pre和当前值,如果小于当前值,更新pre,否则,将right置为错误即可
/** * 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 right = true; long int pre = -9999999999; bool isValidBST(TreeNode* root) { inOrder(root); return right; } void inOrder(TreeNode* root) { if(!root) return; inOrder(root->left); if(pre < root->val) pre = root->val; else right = false; inOrder(root->right); } };