题目大意:判断一棵二叉树是否为搜索二叉树。
搜索二叉树的定义是,任何节点如果左子树有节点,则节点的值皆比其小,右子树的节点比其大。
在递归变量二叉树时可以同时传入一个上限值,比如左子树的上限是根节点的值,右子树的下限是根节点的值。这样代码就很好写了
下面是AC的代码,虽然不严谨,但能说明思路
/**
* 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 judge(TreeNode *root,int max,int min)
{
if(!root)return true;
if(root->val >=max || root->val<=min)return false;
if(!judge(root->left,root->val,min))return false;
return judge(root->right,max,min);
}
bool isValidBST(TreeNode *root) {
if(!root)return true;
if(!judge(root->left,root->val,-1000000000))return false;
return judge(root->right,1000000000,root->val);
}
};