您的位置:首页 > 其它

Leetcode Validate Binary Search Tree

2016-12-28 16:02 411 查看
题意:判断二叉搜索树是否合法。

思路:对每个父子结点进行判断,利用左右子树的最大最小值进行判断。

/**
* 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 == NULL) return true;
if(root->left != NULL && root->val <= root->left->val) return false;
if(root->right != NULL && root->val >= root->right->val) return false;

bool bl = true;
bool br = true;

if(root->left) bl = isValidBST(root->left);
if(root->right) br = isValidBST(root->right);

bool fl = true;
bool fr = true;
if(root->right && root->val >= findMin(root->right)) fr = false;
if(root->left && root->val <= findMax(root->left)) fl = false;

if( fr && fl) return true;

return false;
}

int findMin(TreeNode* root) {
int l = INT_MAX, r = INT_MAX;

if(root->left) l = findMin(root->left);
if(root->right) r = findMin(root->right);

return min(root->val, min(l, r));
}

int findMax(TreeNode* root) {
int l = INT_MIN, r = INT_MIN;

if(root->left) l = findMax(root->left);
if(root->right) r = findMax(root->right);

return max(root->val, max(l, r));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  搜索 dfs leetcode