- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to convert level order binary tree traversal to linked list in Python
Suppose we have a binary search tree, we have to convert it to a singly linked list using levelorder traversal.
So, if the input is like
then the output will be [5, 4, 10, 2, 7, 15, ]
To solve this, we will follow these steps −
head := a new linked list node
currNode := head
q := a list with value root
while q is not empty, do
curr := delete first element from q
if curr is not null, then
next of currNode := a new linked list node with value of curr
currNode := next of currNode
insert left of curr at the end of q
insert right curr at the end of q
return next of head
Let us see the following implementation to get better understanding −
Example
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 ob = Solution() 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) head = ob.solve(root) print_list(head)
Input
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) head = ob.solve(root)
Output
[5, 4, 10, 2, 7, 15, ]
Advertisements
To Continue Learning Please Login
Login with Google