-
Notifications
You must be signed in to change notification settings - Fork 0
/
一棵树上的最远距离
76 lines (62 loc) · 2.06 KB
/
一棵树上的最远距离
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
72
73
74
75
76
class ReturnType():
def __init__(self, height, maxDistance):
self.height = height
self.maxDistance = maxDistance
class TreeNode():
def __init__(self, elem = None, lchild = None, rchild = None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class Tree():
def __init__(self):
self.root = None
def add(self, elem = None):
new_node = TreeNode(elem)
if self.root is None:
self.root = new_node
else:
myQueue = [self.root]
while True:
cur = myQueue.pop(0)
if cur.elem != None:
if cur.lchild is None:
cur.lchild = new_node
break
elif cur.rchild is None:
cur.rchild = new_node
break
else:
myQueue.append(cur.lchild)
myQueue.append(cur.rchild)
def printTree(root):
print("Binary Tree:")
printInOrder(root, 0, 'H', 17)
def printInOrder(root, height, s, length):
if root is None:
return
printInOrder(root.rchild, height + 1, 'v', length)
val = s + str(root.elem) + s
lenM = len(val)
lenL = (length - lenM) // 2
lenR = length - lenM -lenL
val = getSpace(lenL) + val + getSpace(lenR)
print(getSpace(height * length) +val)
printInOrder(root.lchild, height + 1, '^', length)
def getSpace(num):
return ' ' * num
def getMaxDistance(root):
return process(root).maxDistance
def process(root):
if (not root) or (not root.elem):
return ReturnType(0,0)
leftinfo = process(root.lchild)
rightinfo = process(root.rchild)
height = max(leftinfo.height, rightinfo.height) + 1
maxDistance = max(leftinfo.maxDistance, rightinfo.maxDistance, leftinfo.height+rightinfo.height+1)
return ReturnType(height, maxDistance)
t = Tree()
l = [1, 2, None, 4, 5, 6, None, None, 7, 8,None,9,None]
for each in l:
t.add(each)
printTree(t.root)
print(getMaxDistance(t.root))