Binary Tree,Strict Binary Tree and Complete Binary Tree - Duration: 8:46. University Academy- Formerly-IP University CSE/IT 28,921 views.
![]()
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.For example, below binary trees are completeApproach 1: Level Order Traversal (BFS)We can modify to check if given binary tree is complete binary tree or not. The idea is for every dequeued node, we check if it is full node (have both left and right children). If we found a node that is not a full node i.e either it has no children or only 1 child, then all the remaining nodes in the queue should not have any children. If anyone of them has a child then its not complete binary tree else it is. The time complexity of above solution is O(n) and auxiliary space used by the program is O(n).Approach 2: Array representation of complete treeWe can solve this problem by using properties of a complete binary tree.
We know that in array representation of binary tree, the left child for a node at index i is present at index 2i+1 and right child is present at index 2i+2. If we construct an array with all the elements in the tree at the corresponding positions, then for a complete binary tree, the elements will hold consecutive positions.
If any vacant position is found, then tree cannot be a complete tree. The time complexity of above solution is O(n) and auxiliary space used by the program is O(n).Approach 3: Space Optimized previous approachAbove approach takes extra space for storage of boolean array. As discussed for a complete binary tree, the index of left and right child for any node is less than number of nodes for every node. We can avoid using extra space by passing index as a parameter in recursion and check for every node that their left and right child’s index are within correct range.
Comments are closed.
|
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |