📅  最后修改于: 2023-12-03 14:58:19.161000             🧑  作者: Mango
This is a question from the Graduate Aptitude Test in Engineering (GATE) for Computer Science in 2008. The question involves programming and is aimed at testing your understanding of algorithms and data structures.
Given a binary tree, write a function to check if it is a binary search tree (BST). A BST is defined as follows:
We can solve this problem by implementing a recursive function that checks each node in the binary tree. For each node, we check if its value is within a certain range, and recursively call the function on its left and right subtrees.
Here is the implementation in Python:
def isBST(root, minVal=float('-inf'), maxVal=float('inf')):
if not root:
return True
if root.val <= minVal or root.val >= maxVal:
return False
return isBST(root.left, minVal, root.val) and isBST(root.right, root.val, maxVal)
In this solution, root
is the root node of the binary tree, minVal
and maxVal
are the minimum and maximum values allowed for a node. We use float('-inf')
and float('inf')
as the initial values for minVal
and maxVal
, respectively, to ensure that all values are valid. If a node's value is not within the range, we return False
. Otherwise, we recursively call the function on its left and right subtrees.
This problem tests your understanding of binary search trees and recursion. It is important to remember that a binary search tree must satisfy certain conditions, and we can implement a recursive function to check each node in the tree.