性质:二叉搜索树中序遍历是严格递增序列
做法:遍历时比较当前值和前一个值之间的大小关系即可
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (root == nullptr) {
return true;
}
bool flag = true;
int pre_num = 0;
std::stack<TreeNode *> stack_;
while (root || !stack_.empty()) {
while (root) {
stack_.push(root);
root = root->left;
}
TreeNode *node = stack_.top();
stack_.pop();
if (flag) {
flag = false;
} else {
if (pre_num >= node->val) {
return false;
}
}
pre_num = node->val;
root = node->right;
}
return true;
}
};