-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListofDepth.py
71 lines (64 loc) · 1.76 KB
/
ListofDepth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Created by Elshad Karimov
# Copyright © AppMillers. All rights reserved.
# List of Depth
class LinkedList:
def __init__(self, val):
self.val = val
self.next = None
def add(self, val):
if self.next == None:
self.next = LinkedList(val)
else:
self.next.add(val)
def __str__(self):
return "({val})".format(val = self.val) + str(self.next)
class BinaryTree:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def depth(tree):
if tree == None:
return 0
if tree.left == None and tree.right == None:
return 1
else:
depthLeft = 1 + depth(tree.left)
depthRight = 1 + depth(tree.right)
if depthLeft > depthRight:
return depthLeft
else:
return depthRight
def treeToLinkedList(tree, custDict = {}, d = None):
if d == None:
d = depth(tree)
if custDict.get(d) == None:
custDict[d] = LinkedList(tree.val)
else:
custDict[d].add(tree.val)
if d == 1:
return custDict
if tree.left != None:
custDict = treeToLinkedList(tree.left, custDict, d-1)
if tree.right != None:
custDict = treeToLinkedList(tree.right, custDict, d-1)
return custDict
mainTree = BinaryTree(1)
two = BinaryTree(2)
three = BinaryTree(3)
four = BinaryTree(4)
five = BinaryTree(5)
six = BinaryTree(6)
seven = BinaryTree(7)
mainTree.left = two
mainTree.right = three
two.left = four
two.right = five
three.left = six
three.right = seven
custDict = treeToLinkedList(mainTree)
print(custDict[3])
print(custDict[2])
print(custDict[1])
# for depthLevel, linkedList in custDict.items():
# print("{0} {1}".format(depthLevel, linkedList))