forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Number_Of_Possible_Binary_Tree_Topologies.py
50 lines (38 loc) · 1.49 KB
/
Number_Of_Possible_Binary_Tree_Topologies.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
# Solution 1
# Upper Bound: O((n*(2nn)!) / (n!(n+1)!)) time | O(n) space
def numberOfBinaryTreeTopologies(n):
if n == 0:
return 1
numberOfTotalTrees = 0
for leftTreeSize in range(n):
rightTreeSize = n - 1 - leftTreeSize
numberOfLeftTree = numberOfBinaryTreeTopologies(leftTreeSize)
numberOfRightTree = numberOfBinaryTreeTopologies(rightTreeSize)
numberOfTotalTrees += numberOfLeftTree * numberOfRightTree
return numberOfTotalTrees
# Solution 2
# Upper Bound: O(n^2) time | O(n) space
def numberOfBinaryTreeTopologies(n, cache = {0: 1}):
if n in cache:
return cache[n]
numberOfTotalTrees = 0
for leftTreeSize in range(n):
rightTreeSize = n - 1 - leftTreeSize
numberOfLeftTree = numberOfBinaryTreeTopologies(leftTreeSize, cache)
numberOfRightTree = numberOfBinaryTreeTopologies(rightTreeSize, cache)
numberOfTotalTrees += numberOfLeftTree * numberOfRightTree
cache[n] = numberOfTotalTrees
return numberOfTotalTrees
# Solution 3
# O(n^2) time | O(n) space
def numberOfBinaryTreeTopologies(n):
cache = [1]
for m in range(1, n + 1):
numberOfTotalTrees = 0
for leftTreeSize in range(m):
rightTreeSize = m - 1 - leftTreeSize
numberOfLeftTree = cache[leftTreeSize]
numberOfRightTree = cache[rightTreeSize]
numberOfTotalTrees += numberOfLeftTree * numberOfRightTree
cache.append(numberOfTotalTrees)
return cache[n]