题解 | #判断是不是二叉搜索树#
判断是不是二叉搜索树
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) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return bool布尔型 */ bool isValidBST(TreeNode* root) { // write code here // 递归判断是否符合 auto [isTree, maxValue] = GetMax(root); return isTree; } pair<bool, int> GetMax(TreeNode* root){ // 返回该分支最大值和是否是二叉搜索树的pair // 递归判断是否符合 int max; bool isValidLeft = true; max = root->val; if(root->left != nullptr){ auto [isLeft, maxLeft] = GetMax(root->left); cout<<"left,"<<maxLeft<<endl; if(root->val > maxLeft&&isLeft){ isValidLeft = true; } else{ isValidLeft = false; } } bool isValidRight; if(root->right != nullptr){ auto [isRight, maxRight] = GetMax(root->right); cout<<"right,"<<maxRight<<endl; if(root->val<maxRight&&isRight){ isValidRight= true; max = maxRight; } else{ isValidLeft = false; } } // 当前内容展示 if(isValidLeft&&isValidLeft){ return pair(true, max); } else{ return pair(false, max); } } };