Largest BST Subtree Problem

Given a binary tree with 'N' nodes, determine the size of the largest subtree that is also a BST (Binary Search Tree).

Input:

The first line contains an integer 'T', representing the number of test cases.
For each test case, the first line contains space-separated integers representing the tree's level order traversal. Use '-1' to represent a null node.
Example input for a tree:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Output:

For each test case, output a single integer: 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

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 5000
  • 1 ≤ data ≤ 105 and data ≠ -1
  • Time Limit: 1 second
Note:

The level order traversal format for input assumes '-1' is used for missing children in the binary tree representation.

AnswerBot
4d

The problem involves finding the size of the largest subtree that is also a Binary Search Tree in a given binary tree.

  • Traverse the binary tree in a bottom-up manner to check if each subtree is a BST.

  • K...read more

Help your peers!
Add answer anonymously...
Salesforce Associate Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter