-
Notifications
You must be signed in to change notification settings - Fork 8
/
numberOfBinaryTreeTopologies.py
40 lines (35 loc) · 1.35 KB
/
numberOfBinaryTreeTopologies.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
# def numberOfBinaryTreeTopologies(n):
# if n == 0:
# return 1
# numberOfTrees =0
# for leftTreeSize in range(0,n):
# rightTreeSize = n - 1 - leftTreeSize
# numberOfTreeLeft = numberOfBinaryTreeTopologies(leftTreeSize)
# numberOfTreeRight = numberOfBinaryTreeTopologies(rightTreeSize)
# numberOfTrees+=numberOfTreeLeft*numberOfTreeRight
# return numberOfTrees
# def numberOfBinaryTreeTopologies(n,cache={0:1}):
# if n in cache:
# return cache[n]
# numberOfTrees =0
# for leftTreeSize in range(0,n):
# rightTreeSize = n - 1 - leftTreeSize
# numberOfTreeLeft = numberOfBinaryTreeTopologies(leftTreeSize,cache)
# numberOfTreeRight = numberOfBinaryTreeTopologies(rightTreeSize,cache)
# numberOfTrees+=numberOfTreeLeft*numberOfTreeRight
# cache[n]=numberOfTrees
# return numberOfTrees
def numberOfBinaryTreeTopologies(n):
cache = [1]
for m in range(1, n+1):
numberOfTrees = 0
for leftTreeSize in range(m):
rightTreeSize = m-1-leftTreeSize
numberOfLeftTrees = cache[leftTreeSize]
numberOfRightTrees = cache[rightTreeSize]
numberOfTrees += numberOfLeftTrees * numberOfRightTrees
cache.append(
numberOfTrees
)
return cache[n]
print(numberOfBinaryTreeTopologies(3))