Check if the Binary Tree contains a balanced BST of size K
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)
My Personal Notes arrow_drop_up