📜  门| GATE-CS-2009 |问题3(1)

📅  最后修改于: 2023-12-03 15:28:43.520000             🧑  作者: Mango

GATE-CS-2009 Question 3

This is a programming question from the GATE-CS-2009 exam. The question requires the programmer to implement a function that checks if a given binary tree is a binary search tree or not. The specific requirements and details are given below.

Problem Statement

Given a binary tree as input, implement a function isBST that checks if the binary tree is a binary search tree or not. The function should return true if the given binary tree is a binary search tree and false otherwise.

Function Signature:

def isBST(root: TreeNode) -> bool:
    pass

Input

  • root: the root node of the binary tree

Output

  • True if the binary tree is a binary search tree
  • False otherwise
Approach

The approach to solve this problem is to check if the order of elements in the binary tree follows the binary search tree property. The binary search tree property is, for a node x, all the nodes in the left subtree of x have keys less than x, and all nodes in the right subtree of x have keys greater than x.

We can perform an inorder traversal of the binary tree and store the elements in an array. If the array is sorted, then the binary tree follows the binary search tree property.

Pseudo Code
def isBST(root: TreeNode) -> bool:
    # perform an inorder traversal and store elements in an array
    array = inorderTraversal(root)
    
    # check if the array is sorted
    for i in range(len(array)-1):
        if array[i] >= array[i+1]:
            return False
    return True
Code

Here is the python implementation of isBST function:

def isBST(root: TreeNode) -> bool:
    def inorderTraversal(node):
        if not node:
            return []
        return inorderTraversal(node.left) + [node.val] + inorderTraversal(node.right)
    
    # perform an inorder traversal and store elements in an array
    array = inorderTraversal(root)
    
    # check if the array is sorted
    for i in range(len(array)-1):
        if array[i] >= array[i+1]:
            return False
    return True
Complexity Analysis

The time complexity of isBST function is O(n), where n is the number of nodes in the binary tree. This is because we need to perform an inorder traversal of the binary tree to store elements in the array, which takes O(n) time. Additionally, we need to check if the array is sorted, which takes O(n) time as we need to compare each element with its adjacent element.

The space complexity of isBST function is O(n), where n is the number of nodes in the binary tree. This is because we are storing all the elements in the array during the inorder traversal, which takes O(n) space.

Conclusion

In this problem, we have seen how to determine if a given binary tree is a binary search tree or not. We have implemented an isBST function that uses inorder traversal to store the elements in the binary tree in an array and checks if the array is sorted or not.