My solution passes all cases, but I'm unsure what the runtime and space complexity would be. Would it be O(2^depth) since it recursively searches branches possibly spawning 2 more runs in each call? And I'm assuming its space complexity is O(n) where n = nodes in the tree? I'm really bad at wrapping my head around space/time complexity for recursive problems
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
In case that solution is O(2^d), I tried to write an O(n) solution:
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
This solution also passes and both are 64% faster than avg, so I'm a little confused, how are they the same runtime?
Another question I had about my 2nd solution was that it only worked when I had
return recurse(root.left, node, root.val, depth) or recurse(root.right, node, root.val, depth)
instead of
recurse(root.left, node, root.val, depth)
recurse(root.right, node, root.val, depth)
I don't really understand why the latter wouldn't work - I get the error TypeError: cannot unpack non-iterable NoneType object