98 Validate Binary Search Tree

Solution:
lbd, ubd method

/**
 * 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 isValidsubBST(TreeNode* root, int lbd, int ubd) {
        if ( root == NULL ) return true;
        if ( root->val <= lbd or root->val >= ubd) return false;
        bool left = isValidsubBST(root->left, lbd, root->val);
        bool right = isValidsubBST(root->right, root->val, ubd);
        return (left and right);
    }
    bool isValidBST(TreeNode* root) {
        return isValidsubBST(root, INT_MIN, INT_MAX);
    }
};

Inorder method

/**
 * 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:
    vector<int> inOrder(TreeNode* root) {
        vector<int> res;
        if ( root == NULL ) return res;
        auto left = inOrder(root->left);
        auto right = inOrder(root->right);
        left.push_back(root->val);
        int nres = right.size();
        for ( int i = 0; i <= nres; i++ ) left.push_back(right[i]);
        return left;
    }
    bool isValidBST(TreeNode* root) {
        vector<int> res = inOrder(root);
        int nres = res.size();
        if ( nres <= 1 ) return true;
        for ( int i = 0; i <= nres-2; i++) {
            if ( res[i] >= res[i+1] ) return false;
        }
        return true;
    }
};

Recursive method

/**
 * 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:
    int rightMost(TreeNode* root) {
        while ( root->right != NULL ) root = root->right;
        return root->val;
    }
    int leftMost(TreeNode* root) {
        while ( root->left != NULL ) root = root->left;
        return root->val;
    }
    bool isValidBST(TreeNode* root) {
        if ( root == NULL ) return true;
        bool left = true, right = true;
        if ( root->left != NULL ) left = root->val > rightMost(root->left) and isValidBST(root->left);
        if ( root->right != NULL ) right = root->val < leftMost(root->right) and isValidBST(root->right);
        return (left and right);
    }
};

results matching ""

    No results matching ""