题解 | #判断是不是二叉搜索树#中序遍历
判断是不是二叉搜索树
https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <climits> #include <iterator> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return bool布尔型 */ bool isValidBST(TreeNode* root) { // 因为不止需要判断是否比父母大 /小,还需要判断是否比祖先大/小,深度优先搜索 deque<TreeNode*> workStack({root}); TreeNode *cur,*previous=new TreeNode(-1),*lastVisited=new TreeNode(INT_MIN); previous->left=root; while(workStack.size()){ cur=workStack.back(); if(cur->left && (cur==previous->left||cur==previous->right)){ workStack.push_back(cur->left); }else{ workStack.pop_back(); if(cur->val<=lastVisited->val)return false; lastVisited=cur; if(cur->right)workStack.push_back(cur->right); } previous=cur; } return true; } };