leetcode-98. 验证二叉搜索树

 

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
// class Solution {
// public:
//     bool isValidBST(TreeNode* root) {
//         if(root==NULL)
//             return true;
//         if(root->left==NULL&&root->right==NULL){
//             cout<<"falg: "<<root->val<<endl;
//             return true;
//         }
//         if(root->left&&root->right){
//             if(root->val > root->left->val&&root->val < root->right->val)
//                 if(isValidBST(root->left)&&isValidBST(root->right))
//                     return true;
//                 else 
//                     return false;
//             else
//                 return false;
//         }else if(root->left&&!root->right){
//             if(root->val > root->left->val)
//                 if(isValidBST(root->left))
//                     return true;
//                 else
//                     return false;
//             else
//                 return false;
//         }else if(root->right&&!root->left){
//             if(root->val<root->right->val)
//                 if(isValidBST(root->right))
//                     return true;
//                 else 
//                     return false;
//             else 
//                 return false;
//         }else
//             return true;
//     }
// };

class Solution {
public:
    vector<int> res;
    bool isValidBST(TreeNode* root) {
        if(root==NULL)
            return true;
        inorder(root);  // 先中序遍历,在判断是否有大小不对的情况。
        for(int i = 0; i < res.size()-1; i++){
            if(res[i]>=res[i+1])
                return false;
        }
        return true;
        
    }
    void inorder(TreeNode* root){
        if(root==NULL)
            return;
        if(root->left)
            inorder(root->left);
        res.push_back(root->val);
        if(root->right)
            inorder(root->right);
    }

};

 

posted @ 2021-07-17 19:27  三一一一317  阅读(32)  评论(0)    收藏  举报