![]() |
Given a Binary Tree, Our task is to check whether the given Binary Tree is a Complete Binary Tree or not in JavaScript. A complete binary tree is one where every level is filled except possibly the last level and all nodes are positioned as far to the left as possible. Example: Below the tree is a Complete Binary Tree: ![]() Complete Binary Tree Below are the approaches to check if a binary tree is complete using JavaScript: Table of Content Using IterationIn this approach, we traverse the binary tree level by level using a queue. At each level, we check if there are any missing nodes before any non-null node. If we encounter a node with one child while there are still nodes with two children, the tree cannot be complete. Similarly, if we encounter a node with no children or only a left child, all the following nodes should also have no children. If any violation of these conditions is found during traversal, we return false otherwise the tree is complete. Example: The example below checks if a binary tree is complete Using Iteration.
Output Is the binary tree complete? true Time Complexity: O(n) where n is the number of nodes in a given Binary Tree. Auxiliary Space: O(h) where h is the height of the given Binary Tree. Using RecursionIn this approach, we first count the number of nodes in the binary tree. Then, we recursively traverse the tree and check if the indices assigned to each node follow the complete binary tree property. If any node’s index is greater than or equal to the total number of nodes in the tree, the tree cannot be complete. Example: The below example checks if a binary tree is complete Using Recursion.
Output Is the binary tree complete? true Time Complexity: O(N) where N is the number of nodes in the tree. Space Complexity: O(h) where h is the height of the given tree. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |