Valid Binary Search Tree

1) In every possible step, you should consider whether left or right subtree exists or not;

code


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class ReturnType
{
public:
    long maxval;
    long minval;
    bool isBST;
    ReturnType(long maxval, long minval, bool isBST)
    {
        this->maxval = maxval;
        this->minval = minval;
        this->isBST = isBST;
    }
};

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return helper(root).isBST;
    }

    ReturnType helper(TreeNode* root)
    {
        if(root == NULL)
        {
            //return ReturnType(INT_MIN-1, INT_MAX+1, true);
            return ReturnType(0, 0, true);
        }

        ReturnType left = helper(root->left);
        ReturnType right = helper(root->right);
        if(left.isBST == false || right.isBST == false)
        {
            return ReturnType(0, 0, false);
        }

        if(root->left != NULL && root->val <= left.maxval)
        {
            return ReturnType(0, 0, false);
        }

        if(root->right != NULL && root->val >= right.minval)
        {
            return ReturnType(0, 0, false);
        }

        long maxVal = root->right==NULL?(long)root->val:right.maxval;
        long minVal = root->left==NULL?(long)root->val:left.minval;

        return ReturnType(maxVal, minVal, true);
    }
};

results matching ""

    No results matching ""