📅  最后修改于: 2023-12-03 15:28:39.453000             🧑  作者: Mango
This is a problem from the GATE Computer Science Mock Test 2018. It pertains to a situation where we have a binary tree and we want to determine if it is a binary search tree.
Suppose we have a binary tree with N nodes. We want to determine whether the given binary tree is a binary search tree or not. Implement a function CheckBST(root)
that takes the root of the binary tree as input and returns true if the binary tree is a binary search tree, and false otherwise.
The function signature is as follows:
def CheckBST(root: TreeNode) -> bool:
The basic approach to solve the problem is to traverse the binary tree and check if it satisfies the properties of a binary search tree. A binary search tree has the following properties:
To implement this, we traverse the binary tree using an in-order traversal. In an in-order traversal, we visit a node's left subtree, then the node itself, and then its right subtree. If the elements of the binary tree are sorted in ascending order during the traversal, then it is a binary search tree. We maintain a variable prev
which stores the previous element of the traversal. If the current element is less than the previous element, then it is not a binary search tree.
The following is the pseudo code for the function:
def CheckBST(root: TreeNode) -> bool:
def inorder(node: TreeNode) -> bool:
nonlocal prev
if node is None:
return True
if not inorder(node.left):
return False
if node.value < prev:
return False
prev = node.value
return inorder(node.right)
prev = float('-inf')
return inorder(root)
Here we are making use of a helper function inorder()
which conducts the in-order traversal and returns a boolean value indicating whether the binary tree is a binary search tree or not.
The time complexity of the above algorithm is O(n) since we are traversing each node exactly once. The space complexity of the algorithm is O(h), where h is the height of the binary tree. This is because the recursion stack used by the algorithm is maximum the height of the tree.
Thus, we have successfully implemented the CheckBST()
function which determines if the binary tree is a binary search tree or not. The algorithm has a time complexity of O(n) and a space complexity of O(h).