Most Tree Questions can be solved using the following approach:
def treeFunc(root, **other params): if(root==null): return baseCase/other relevant params val=operation(treeFunc(root.left), treeFunc(root.right)) return val
A lot of recursion works the same way
Merge 2 Binary Trees:
def merge(t1, t2):
if not t1 and not t2:
return None
elif not t1:
return t2
elif not t2:
return t1
else:
node = Node(t1.data + t2.data)
node.left = merge(t1.left, t2.left)
node.right = merge(t1.right, t2.right)
return node
Ways to Solve Most Tree Question
Merge 2 Binary Trees:
def merge(t1, t2):
if not t1 and not t2:
return None
elif not t1:
return t2
elif not t2:
return t1
else:
node = Node(t1.data + t2.data)
node.left = merge(t1.left, t2.left)
node.right = merge(t1.right, t2.right)
return node