如何判断一个树是否是二叉搜索树
一个小技巧:可以同时传入最小/最大值,并且将初始值设为INT_MIN,INT_MAX,这样,其左子树所有节点的值必须在INT_MIN及根节点的值之间,其右子树所有节点的值必须在根节点的值以及INT_MAX之间。
bool helper(TreeNode *root,int min,int max){if(root == NULL) return true;if((root->val < max || (root->val == max && root->right == NULL))&&(root->val > min || (root->val == min && root->left == NULL))&&(helper(root->left,min,root->val))&&(helper(root->right,root->val,max)))return true;return false;
}bool isValidBST(TreeNode *root){if(root == NULL) return true;return helper(root,INT_MIN,INT_MAX);
}