Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements:

1.The data value of every node in a node's left subtree is less than the data value of that node.

2.The data value of every node in a node's right subtree is greater than the data value of that node.

Given the root node of a binary tree, can you determine if it's also a binary search tree?

Complete the function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must return a boolean denoting whether or not the binary tree is a binary search tree. You may have to write one or more helper functions to complete this challenge.

Example:

Input:  tree[]={3,2,4}
Output: Yes

Approach

C++

#include <bits/stdc++.h>
using namespace std;

struct Node
{
    int data;
    Node *left;
    Node *right;
    Node(int val)
    {
        this->data = val;
        this->left = NULL;
        this->right = NULL;
    }
};
bool BST(Node *rootint min1int max1)
{
    if (root == NULL)
        return true;
    if (root->data <= min1 || root->data >= max1)
        return false;
    return BST(root->leftmin1root->data) && BST(root->rightroot->datamax1);
}
bool checkBST(Node *root)
{
    return BST(root, -1000110001);
}

int main()
{
    Node *root = new Node(3);
    root->left = new Node(2);
    root->right = new Node(4);

    if (checkBST(root))
    {
        cout << "Yes\n";
    }
    else
    {
        cout << "No\n";
    }
    return 0;
}


No comments:

Post a Comment