01(July) Make Binary Tree From Linked List
01. Make Binary Tree From Linked List
The problem can be found at the following link: Question Link
Problem Description
Given a Linked List Representation of a Complete Binary Tree, the task is to construct the Binary Tree and print the level order traversal of the Binary Tree. Note that a complete binary tree is represented in a linked list where if the root node is at position (i), its left and right children are stored at positions ( 2i + 1 ) and ( 2i + 2 ) respectively. The height of the tree is ( H ), and the recursion stack implicitly uses this space.
Example:
Input: n = 5, k = 1->2->3->4->5
Output: 1 2 3 4 5
Explanation: The tree would look like:
1
/ \
2 3
/ \
4 5Now, the level order traversal of the above tree is 1 2 3 4 5.
My Approach
Initialization:
Convert the linked list into an array to simplify index-based access.
Create a helper function to build the tree recursively.
Tree Construction:
Use the helper function to construct the tree by assigning the left and right children using the complete binary tree properties.
Return:
Return the root of the constructed binary tree.
Time and Auxiliary Space Complexity
Expected Time Complexity: (O(n)), as we iterate through the linked list once to build the array and then construct the tree.
Expected Auxiliary Space Complexity: (O(n)), as we use an array of size (n) and the recursion stack space.
Code
C++:
Java:
Python:
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated