您的位置:首页 > 其它

leetcode 98: Validate Binary Search Tree

2015-08-11 13:11 393 查看
The corner case here is that some nodes have the value of INT_MAX and INT_MIN, so the top root should be differentiated from other roots. In my code, I use the minNode=NULL and maxNode=NULL to solve it.

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(!root)
return true;
return helper(root,NULL,NULL);
}
bool helper(TreeNode* root,TreeNode* minNode,TreeNode* maxNode)
{
if(!root)
return true;
if(minNode&&root->val<=minNode->val||maxNode&&root->val>=maxNode->val)
return false;
return helper(root->left,minNode,root)&&helper(root->right,root,maxNode);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: