Largest BST
Submissions: 18011   Accuracy:

30.88%

  Difficulty: Medium   Marks: 4

Given a binary tree, Your task is to complete the function largestBst that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the whole Binary Tree is BST, then return the size of the whole tree.

Input:

The first line of input contains the number of test cases T. For each test case, there will be only a single line of input which is a string representing the tree as described below: 

  1. The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character “N” denotes NULL child.

  2. For example:
     
    For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N

Output:
The function should return the size of the max subtree which is also the BST.

Your Task:
This is a function problem. You don't have to take any input. Just complete the function largestBst() that takes a node as a parameter and return the size of the max subtree which is also the BST.

Constraints:
1 <=T <= 10
1 <= Number of nodes <= 100000
1 <= Data of a node <= 1000000

Example:
Input

2
1 4 4 6 8
6 6 3 N 2 9 3 N 8 8 2

Output
1

2

** For More Input/Output Examples Use 'Expected Output' option **

Author: Shubham Joshi 1


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.