错误解法
class Solution { public: bool isValidBST(TreeNode* root) { if(root == NULL) return true; bool left = isValidBST(root->left); bool right = isValidBST(root->right); if(left == false || right == false) return false; if(root->left != NULL && root->left->val >= root->val) return false; if(root->right != NULL && root->val >= root->right->val) return false; return true; } };
[10,5,15,null,null,6,20]这种情况没考虑到,即这个代码只考虑了当前节点小于左节点、大于右节点,没有递归考虑他的root节点
https://www.cnblogs.com/grandyang/p/4298435.html
class Solution { public: bool isValidBST(TreeNode* root) { return isValid(root,LONG_MIN,LONG_MAX); } bool isValid(TreeNode* root,long left,long right){ if(!root) return true; if(root->val <= left || root->val >= right) return false; return isValid(root->left,left,root->val) && isValid(root->right,root->val,right); } };
98. Validate Binary Search Tree
原文:https://www.cnblogs.com/ymjyqsx/p/10493370.html