Check for valid binary search tree

Determine whether a tree is a valid binary search tree.

A binary search tree is a tree with two children, left and right, and satisfies the constraint that the key in the left the child must be less than or equal to the root and the key in the right the child must be greater than or equal to the root.

Example:

Input:  tree  = [2,1,3]
Output: true

Approach

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
bool isValid(TreeNode *rootlong long min1long long max1)
{
    if (root == NULL)
        return true;
    if (root->data <= min1 || root->data >= max1)
        return false;
    return isValid(root->leftmin1root->data) &&
           isValid(root->rightroot->datamax1);
}
bool isValidBST(TreeNode *root)
{
    return isValid(rootLLONG_MINLLONG_MAX);
}
int main()
{
    TreeNode *root = new TreeNode(2);
    root->left = new TreeNode(1);
    root->right = new TreeNode(3);

    if (isValidBST(root))
        cout << "true";
    else
        cout << "false";
    return 0;
}


No comments:

Post a Comment