题目大意: 判断一个二叉树是否是个排序二叉树,即根节点大于左节点,小于右节点,同时它的左右子树也满足这个要求
解题思路:中序遍历,如果当前节点小于等于左子树的最大节点,则不符合要求,若当前节点大于等于右子树的最小节点,则不符合要求
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
int minVal = INT_MAX, maxVal = INT_MIN;
return isValidBSTAssist(root, minVal, maxVal);
}
private:
bool isValidBSTAssist(TreeNode *root, int &minVal, int &maxVal) {
if(root == NULL) {
return true;
}
int left_min, left_max;
if(!isValidBSTAssist(root->left, left_min, left_max)) {
return false;
}
if(root->left != NULL) {
if(root->val <= left_max) {
return false;
}
} else {
left_min = left_max = root->val;
}
int right_min, right_max;
if(!isValidBSTAssist(root->right, right_min, right_max)) {
return false;
}
if(root->right != NULL) {
if(root->val >= right_min) {
return false;
}
} else {
right_min = right_max = root->val;
}
minVal = min(root->val, min(left_min, right_min));
maxVal = max(root->val, max(left_max, right_max));
return true;
}
};