LeetCode之Validate Binary Search Tree

来源:互联网 发布:linux打包压缩命令 编辑:程序博客网 时间:2024/05/22 10:25
 /*采用中序遍历,判断两个相邻元素是否满足递增规律即可。*/class Solution {public:    bool isValidBST(TreeNode* root) {        if(root == nullptr) return true;        TreeNode *pre(nullptr), *cur(root);        stack<TreeNode*> s;        while(!s.empty() || cur != nullptr){            while(cur != nullptr){                s.push(cur);                cur = cur->left;            }            if(!s.empty()){                cur = s.top();                s.pop();                if(pre != nullptr && pre->val >= cur->val) return false;                pre = cur;                cur = cur->right;            }        }        return true;    }};

0 0