VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-the-binary-tree-contains-a-balanced-bst-of-size-k/

⇱ Check if the Binary Tree contains a balanced BST of size K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if the Binary Tree contains a balanced BST of size K

Last Updated : 15 Jul, 2025

Given a Binary Tree and a positive integer K. The task is to check whether the Balanced BST of size K exists in a given Binary Tree or not. If it exists then print β€œYes” else print β€œNo”.

Examples: 

Input: K = 4,
Below is the given Tree:
 15
 / \
 10 26
 / \ / \
 5 12 25 40
 / / \
 20 35 50
 \
 60
Output: Yes
Explanation: 
Subtree of the given tree with
size k is given below:
 40
 / \
 35 50
 \
 60

Input: K = 4,
Below is the given Tree:
 18
 / 
 9 
 / \
 7 10
Output: No
Explanation:
There is no subtree of size K
which forms a balanced BT.

Approach: The idea is to use the Post Order Traversal. The following are the steps for solving the problem: 

  1. Perform a Post Order Traversal on the given tree and check BST condition for each node where the largest value in the left sub-tree should be smaller than the current value and the smaller value in the right subtree should be greater than the current value.
  2. Then check if the BST is balanced or not that is the absolute difference between left and right sub-tree should be either 0 or 1.
  3. Then pass values return from the sub-trees to the parent.
  4. Perform the above steps for all nodes and take the Boolean variable ans which is initially marked false which is used to check whether a balanced BST is present or not.
  5. If a Balanced BST of size K is found then print "Yes" else print "No".

Below is the implementation of the above approach:


Output: 
Yes

 

Time Complexity: O(N) 
Auxiliary Space: O(1)

Comment