Find the largest Complete Subtree in a given Binary Tree
Given a Binary Tree, the task is to find the size of largest Complete sub-tree in the given Binary Tree.
Complete Binary Tree – A Binary tree is Complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible.
Note: All Perfect Binary Trees are Complete Binary tree but reverse in NOT true. If a tree is not complete then it is also not Perfect Binary Tree.
Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Output: Size : 10 Inorder Traversal : 8 4 9 2 10 5 1 6 3 7 The given tree a complete binary tree. Input: 50 / \ 30 60 / \ / \ 5 20 45 70 / 10 Output: Size : 4 Inorder Traversal : 10 45 60 70
Approach: Simply traverse the tree in bottom up manner. Then on coming up in recursion from child to parent, we can pass information about sub-trees to the parent. The passed information can be used by the parent to do Complete Tree test (for parent node) only in constant time. Both left and right sub-trees need to tell the parent information whether they are perfect or not and complete or not and they also need to return the max size of complete binary tree found till now.
The sub-trees need to pass the following information up the tree for finding the largest Complete sub-tree so that we can compare the maximum size with the parent’s data to check the Complete Binary Tree property.
- There is a bool variable to check whether the left child or the right child sub-tree is Perfect and Complete or not.
- From left and right child calls in recursion we find out if parent sub-tree is Complete or not by following 3 cases:
- If left subtree is perfect and right is complete and there height is also same then sub-tree root is also complete binary subtree with size equal to sum of left and right subtrees plus one (for current root).
- If left subtree is complete and right is perfect and the height of left is greater than right by one then sub-tree root is complete binary subtree with size equal to sum of left and right subtrees plus one (for current root). And root subtree cannot be perfect binary subtree because in this case its left child is not perfect.
- Else this sub-tree cannot be a complete binary tree and simply return the biggest sized complete sub-tree found till now in the left or right sub-trees.And if tree is not complete then it is not perfect also.
Below is the implementation of the above approach:
Size : 4 Inorder Traversal : 10 45 60 70
Time Complexity: O(N), where N is the total number of nodes present in the tree.
Space Complexity: O(N). The size of the stack used for recursion is the same order as the size of the tree