Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to convert level order binary tree traversal to linked list in Python
Converting a binary tree to a singly linked list using level-order traversal means visiting nodes level by level from left to right. We use a queue to perform breadth-first traversal and create linked list nodes in the same order.
Problem Understanding
Given a binary tree like this:
The level-order traversal visits nodes as: 5 ? 4 ? 10 ? 2 ? 7 ? 15, and we create a linked list in this order.
Algorithm Steps
To convert the binary tree to a linked list using level-order traversal:
Create a dummy head node for the linked list
Initialize a queue with the root node
-
While the queue is not empty:
Remove the first node from queue
If the node exists, create a new linked list node with its value
Add the node's left and right children to the queue
Return the linked list starting from dummy head's next
Implementation
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
class TreeNode:
def __init__(self, data, left = None, right = None):
self.val = data
self.left = left
self.right = right
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def solve(self, root):
head = ListNode(None)
currNode = head
q = [root]
while q:
curr = q.pop(0)
if curr:
currNode.next = ListNode(curr.val)
currNode = currNode.next
q.append(curr.left)
q.append(curr.right)
return head.next
# Create the binary tree
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(10)
root.left.left = TreeNode(2)
root.right.left = TreeNode(7)
root.right.right = TreeNode(15)
# Convert to linked list
ob = Solution()
head = ob.solve(root)
print_list(head)
[5, 4, 10, 2, 7, 15, ]
How It Works
The algorithm uses a queue-based breadth-first search approach:
Level 1: Process root (5), add its children to queue
Level 2: Process nodes 4 and 10, add their children
Level 3: Process nodes 2, 7, and 15
Each processed node creates a new linked list node, maintaining the level-order sequence.
Time and Space Complexity
Time Complexity: O(n) where n is the number of nodes in the tree, as we visit each node exactly once.
Space Complexity: O(w) where w is the maximum width of the tree (maximum nodes at any level) for the queue storage.
Conclusion
This approach efficiently converts a binary tree to a linked list using level-order traversal. The queue-based method ensures nodes are processed level by level, creating the linked list in the correct order.
---