二叉树中Leetcode表兄弟的不同python解决方案的运行时

时间:2020-05-07 20:53:10

标签: python recursion time-complexity

我的解决方案可以处理所有情况,但是我不确定运行时和空间的复杂性。是O(2 ^ depth),因为它递归搜索分支,可能在每个调用中又产生2个运行? 我假设其空间复杂度为O(n),其中n =树中的节点?对于递归问题,我实在无法解决时空复杂性问题

class Solution:    
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:

    def recurse(root, depth_dict, depth, parent):
        if root:
            depth_dict[root.val].append(depth)
            depth_dict[root.val].append(parent)

            if root.left or root.right:
                parent = root.val
                depth += 1

            recurse(root.left, depth_dict, depth, parent)
            recurse(root.right, depth_dict, depth, parent)


    depth_dict = defaultdict(list)  # first item = depth, 2nd item = parent
    depth = 0
    parent = None

    recurse(root, depth_dict, depth, parent)

    if depth_dict[x][0] == depth_dict[y][0] and depth_dict[x][1] != depth_dict[y][1]: 
        return True
    return False

如果解决方案是O(2 ^ d),我尝试编写O(n)解决方案:

def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
    def recurse(root, node, parent, depth):
        if root:
            if root.val == node:
                return depth, parent

            depth += 1
            return recurse(root.left, node, root.val, depth) or recurse(root.right, node, root.val, depth)

    depth_x, parent_x = recurse(root,x,None,0)
    depth_y, parent_y = recurse(root,y,None,0)

    if depth_x == depth_y and parent_x != parent_y:
        return True
    return False

此解决方案也通过了,并且两者均比avg快64%,所以我有点困惑,它们如何在同一运行时间?

我对第二个解决方案还有一个疑问,那就是只有在 return recurse(root.left, node, root.val, depth) or recurse(root.right, node, root.val, depth) 代替

recurse(root.left, node, root.val, depth) 
recurse(root.right, node, root.val, depth)

我不太了解后者为什么不起作用-我收到错误TypeError:无法解压缩不可重复的NoneType对象

0 个答案:

没有答案