Here is the solution for your question.
First get maximum value in the depths and decrement level by 1. If consecutive level, then append to previous array. I hope you will get it.
Whenever you try to solve these question, make a plan for how will you
get to the solution and use debugger to see if your code is performing
as you expected or not.
import copy
strings = ["tree", "branch", "leaf", "leaf", "leaf", "branch", "tree", "tree", "branch", "tree"]
depths = [1,2,3,3,3,2,1,1,2,1]
output = copy.deepcopy(depths)
while max(depths)!=0:
m = max(depths)
last = -2
while True:
try:
i = depths.index(m)
depths[i]=m-1
if i-1==last:
output[i-1].append(strings[i] if isinstance(output[i], int) else output[i])
last=i-1
output.pop(i)
depths.pop(i)
strings.pop(i)
continue
else:
output[i] = [strings[i]]
last=i
except:
break
print(output[0])
#output[0] = ['tree', ['branch', ['leaf', 'leaf', 'leaf'], 'branch'], 'tree', 'tree', ['branch'], 'tree']