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:
- 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.
- 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.
- Then pass values return from the sub-trees to the parent.
- 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.
- If a Balanced BST of size K is found then print “Yes” else print “No”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Convert a normal BST to Balanced BST
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Simple Recursive solution to check whether BST contains dead end
- Check whether BST contains Dead End or not
- Sorted Linked List to Balanced BST
- Sorted Array to Balanced BST
- Find if there is a triplet in a Balanced BST that adds to zero
- Find a pair with given sum in a Balanced BST
- Split a BST into two balanced BSTs based on a value K
- A program to check if a binary tree is BST or not
- Check if a Binary Tree (not BST) has duplicate values
- Check if a Binary Tree is BST : Simple and Efficient Approach
- Two nodes of a BST are swapped, correct the BST | Set-2
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Two nodes of a BST are swapped, correct the BST
- Check if a Binary Tree contains node values in strictly increasing and decreasing order at even and odd levels
- How to determine if a binary tree is height-balanced?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.