【发布时间】:2015-12-14 16:41:53
【问题描述】:
我正在练习一些面试问题,并试图弄清楚我的解决方案的时间复杂度以确定给定的二叉树是否平衡。
我相信解决方案 2 的时间复杂度为 O(n),而解决方案 1 的时间复杂度为 O(n^2)。这是因为在解决方案 1 中,您递归到树的底部以检查树是否平衡并检查子树高度的差异。额外的复杂性来自于我们向树的根部更高的备份,get_height 仍然沿树向下递归以计算高度。因此,再次沿着树向下旅行--> O(n^2)。
解决方案 2 首先比较高度的事实意味着,当我们向上移动树时,我们不必再向下检查子树高度。
帮手:
def get_height(root):
if root is None:
return 0
else:
return max(get_height(root.left), get_height(root.right)) + 1
解决方案 1:
def is_balanced(root):
if root is None:
return True
else:
return is_balanced(root.right) and is_balanced(root.left) and (abs(get_height(root.left) - get_height(root.right)) < 2)
解决方案 2:
def is_balanced2(root):
if root is None:
return True
else:
return (abs(get_height(root.left) - get_height(root.right)) < 2) and is_balanced(root.right) and is_balanced(root.left)
检查时差的代码:
s = time.time()
print("result: {}".format(is_balanced(a)))
print("time: {}".format(time.time() - s))
s = time.time()
print("result: {}".format(is_balanced2(a)))
print("time: {}".format(time.time() - s))
不平衡树的结果:
result: False
time: 2.90870666504e-05 # solution 1
result: False
time: 1.50203704834e-05 # solution 2
【问题讨论】: