Header Ad

HackerRank Is This a Binary Search Tree? problem solution

In this tutorial, we are going to solve or make a solution of is this a Binary search Tree? problem. so here we have a pointer to the head or root node of a binary tree, and we need to determine if the binary tree is a binary search tree or not.

HackerRank Is This a Binary Search Tree? problem solution


Problem solution in Python programming.

""" Node is defined as
class node:
  def __init__(self, data):
      self.data = data
      self.left = None
      self.right = None
"""
def check(root, nodes_list):
    if root:
        if check(root.left, nodes_list) == 0:
            return False

        if len(nodes_list) != 0:
            if root.data in nodes_list or root.data < nodes_list[-1]:
                return 0

        nodes_list.append(root.data)

        if check(root.right, nodes_list) == 0:
            return False


def check_binary_search_tree_(root):
    nodes_list = []
    if check(root, nodes_list) in [False, 0]:
        return False
    else:
        return True




Problem solution in Java Programming.

boolean checkBST(Node root) {
        return isBSTNode(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    boolean isBSTNode(Node root, int min, int max){
        boolean isBstNode = false;
        if(root == null){
            return true;
        }
        if(root.data < min || root.data > max){
            return false;
        }
        return (isBSTNode(root.left, min, root.data-1) && isBSTNode(root.right, root.data+1, max));
    }


Problem solution in C++ programming.

/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.  

The Node struct is defined as follows:
    struct Node {
        int data;
        Node* left;
        Node* right;
    }
*/
    bool checkBST(Node* root, int minValue, int maxValue) {
    if (root == NULL) {
        return true;
    }

    if (root->data < minValue || root->data > maxValue) {
        return false;
    }

    return (    checkBST(root->left, minValue, root->data - 1) 
            &&  checkBST(root->right, root->data + 1, maxValue)
            );
}

bool checkBST(Node* root) {
    return checkBST(root, 0, 10000);
}


Post a Comment

0 Comments