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
Selected Reading
Program to convert linked list to zig-zag binary tree in Python
When we have a singly linked list, we can convert it to a binary tree using a specific zig-zag pattern. The conversion follows these rules:
- The head of the linked list becomes the root of the tree
- Each subsequent node becomes the left child if its value is less than the parent, otherwise it becomes the right child
So, if the input is like [2,1,3,4,0,5], then the output will be:
Algorithm
To solve this, we follow these steps:
- Define a function solve() that takes a linked list node
- If node is null, return null
- Create a tree node with the same value as the current linked list node
- If there's a next node in the linked list:
- If next node's value is less than current node's value, make it the left child
- Otherwise, make it the right child
- Return the created tree node
Example
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def print_tree(root):
if root is not None:
print_tree(root.left)
print(root.data, end=', ')
print_tree(root.right)
class Solution:
def solve(self, node):
if not node:
return None
root = TreeNode(node.val)
if node.next:
if node.next.val < node.val:
root.left = self.solve(node.next)
else:
root.right = self.solve(node.next)
return root
# Test the solution
ob = Solution()
linked_list = make_list([2, 1, 3, 4, 0, 5])
result_tree = ob.solve(linked_list)
print_tree(result_tree)
Output
1, 3, 0, 5, 4, 2,
How It Works
The algorithm processes the linked list recursively. Starting from the head (value 2), it compares each subsequent node:
- 1 < 2, so 1 goes to the left of 2
- 3 > 1, so 3 goes to the right of 1
- 4 > 3, so 4 goes to the right of 3
- 0 < 4, so 0 goes to the left of 4
- 5 > 0, so 5 goes to the right of 0
The tree traversal (inorder) produces: 1, 3, 0, 5, 4, 2
Conclusion
This algorithm converts a linked list to a zig-zag binary tree by comparing each node with its predecessor and placing it left or right accordingly. The recursive approach ensures each node finds its proper position in the tree structure.
Advertisements
