Size of Largest BST in a Binary Tree
Given a binary tree with 'N' nodes, determine the size of the largest subtree that is also a Binary Search Tree (BST).
Explanation:
A Binary Search Tree (BST) is defined as follows:
- The left subtree of a node contains only nodes with values less than the node’s value.
- The right subtree of a node contains only nodes with values greater than the node’s value.
- Both the left and right subtrees must also be binary search trees.
Input:
The first line contains an integer 'T', representing the number of test cases. Each test case follows: A single line with space-separated values representing the binary tree in level order. Use -1 for null nodes.
Output:
For each test case, return an integer that indicates the size of the largest BST subtree within the binary tree.
Example:
Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
3
Explanation: In the given tree, the largest subtree that is also a BST has 3 nodes.
Constraints:
- 1 <= T <= 100
- 1 <= N <= 5000
- 1 <= data <= 105 and data != -1
Note: You do not need to print anything; simply implement the function to return the result.
AnswerBot
4d
Find the size of the largest BST subtree in a binary tree.
Traverse the tree in a bottom-up manner to check if each subtree is a BST.
Keep track of the size of the largest BST found so far.
Recursively c...read more
Help your peers!
Add answer anonymously...
Top Josh Technology Group Software Developer interview questions & answers
Popular interview questions of Software Developer
>
Josh Technology Group Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app