2024年12月25日 星期三

find leaves

 # ans1:

from collections import defaultdict

tree = [[], [2, 3], [4, 5], [6], [], [], []]

td = defaultdict(list)

for i in range(len(tree)):

td[i] = tree[i] # 無論是否有子節點,都加入到字典中


# 找到葉節點

def find_leaves(td):

return [node for node in td if not td[node] and node!=0]


print(find_leaves(td))


# ans2

def find_leaves2(tree):

return [i for i,child in enumerate(tree) if not child and not i==0 ]

print(find_leaves2(tree))

沒有留言:

張貼留言