Check whether a Binary Tree is BST (Binary Search Tree) or not
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
Algorithm:
From the definition of BST, it may seem that for a binary tree to be BST, it’s enough to check for each node if the node on its left is smaller & node on its right is greater. But this is actually the wrong approach since it will give wrong output for many test-cases.
The correct algorithm is to check for each node whether the maximum of the left subtree is lesser than the node & the minimum of the right subtree is greater than the node. This algorithm works perfect but not efficient in terms of time complexity.
Intuition says that the in-order traversal for the BST results in a sorted list of nodes and we use this in our algorithm.
Example 1:
Clearly Example 1 is a binary search tree. We will check out further through our function.
Example 2:
Clearly Example 2 is not a binary tree. We will check out through our function.
C++ class implementation for tree
C++ function checkBST for implementation
C++ implementation for creating tree nodes
Main driver function for example1
Main driver function for example2
Output 1
Output 2
need an explanation for this answer? contact us directly to get an explanation for this answer