您的位置:首页 > 其它

LeetCode 98 Validate Binary Search Tree判断是否为合法二叉树

2016-02-12 14:50 543 查看
/**
* 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 Left(TreeNode* left, int root){
while(left->right != NULL){
left = left->right;
}
return left->val < root;
}
bool Right(TreeNode* right,int root){
while(right->left != NULL)
right = right->left;
return right->val > root;
}

bool isValidBST(TreeNode* root) {
if(root == NULL) return true;
int left = 0, right = 0;
bool lres = true,rres = true;
if(root->left){//不为空的情况下
left = 1;
if(root->left->val >= root->val) return false;
lres = isValidBST(root->left);
if(lres) lres = Left(root->left,root->val);//在左儿子是合法二叉树的情况下,检验左儿子的最大值(即一直取左儿子的右儿子)是否小于root值
else return false;
}
if(root->right){
right = 1;
if(root->right->val <= root->val) return false;
rres = isValidBST(root->right);
if(rres) rres = Right(root->right,root->val);
else return false;
}
return lres && rres;
}

};


合法二叉树条件:1、左儿子均小于根,右儿子均大于根 2、左儿子、右儿子均为合法二叉树
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: