判断二叉树为二叉搜索树

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    ////方法1:每个结点都对应一个上限,一个下限。
    bool isValidBST(TreeNode *root) {
        return helper(root,INT_MIN,INT_MAX);
    }
    bool helper(TreeNode *root,int low,int upper){
        if(root==NULL){
            return true;
        }
        if(root->val<=low||root->val>=upper){// 二查搜索数 不能有等于
            return false;
        }
        
        return helper(root->left,low,root->val)&&helper(root->right,root->val,upper);
        
    }
    
};

 */

class Solution {
public:
    ////方法1:每个结点都对应一个上限,一个下限。
    bool isValidBST(TreeNode *root) {
        return helper(root,INT_MIN,INT_MAX);
    }
    bool helper(TreeNode *root,int low,int upper){
        if(root==NULL){
            return true;
        }
        if(root->val<=low||root->val>=upper){// 二查搜索数 不能有等于
            return false;
        }
        
        return helper(root->left,low,root->val)&&helper(root->right,root->val,upper);
        
    }
    
};

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/86208773