Skip to content

Instantly share code, notes, and snippets.

@gvx
Forked from nathanleclaire/treeToLinkedLists.py
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gvx/9356314 to your computer and use it in GitHub Desktop.
Save gvx/9356314 to your computer and use it in GitHub Desktop.
class LinkedList:
next = None
val = None
def __init__(self, val):
self.val = val
def add(self, val):
if self.next is None:
self.next = LinkedList(val)
else:
self.next.add(val)
def __str__(self):
return "({val}) {next}".format(val=self.val, next=self.next)
class BinaryTree:
val = None
left = None
right = None
def __init__(self, val):
self.val = val
def __str__(self):
return "<Binary Tree (val is {val}). \n\tleft is {left} \n\tright is {right}>".format(val=self.val, left=self.left, right=self.right)
def depth(tree):
if tree is None:
return 0
return 1 + max(depth(tree.left), depth(tree.right))
def tree_to_linked_lists(tree, lists=None, d=None):
if lists is None:
lists = {}
if d is None:
d = depth(tree)
if d in lists:
lists[d].add(tree.val)
else:
lists[d] = LinkedList(tree.val)
if tree.left is not None:
tree_to_linked_lists(tree.left, lists, d - 1)
if tree.right is not None:
tree_to_linked_lists(tree.right, lists, d - 1)
return lists
if __name__ == '__main__':
mainTree = BinaryTree(1)
mainTree.left = BinaryTree(2)
mainTree.right = BinaryTree(3)
mainTree.left.left = BinaryTree(4)
mainTree.left.right = BinaryTree(5)
mainTree.right.left = BinaryTree(6)
mainTree.right.right = BinaryTree(7)
mainTree.right.right.right = BinaryTree(8)
mainTree.left.left.left = BinaryTree(9)
ttll = tree_to_linked_lists(mainTree)
for depthLevel, linkedList in ttll.iteritems():
print depthLevel, linkedList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment