python - Counting all nodes of all paths from root to leaves -
if given tree nodes integers: 1 ~ 10, , branching factor of 3 nodes, how can write function traverses through tree counting root leaves every paths
so example, let's needs return this:
{1: 1, 2: 5} i've tried helper function:
def tree_lengths(t): temp = [] in t.children: temp.append(1) temp += [e + 1 e in tree_lengths(i)] return temp there many errors code. one, leaves behind imprints of every visited node in traversal in returning list - it's difficult figure out ones values need list. another, if tree large, not leave behind imprints of root , earlier nodes in path prior reaching line "for in t.children". needs first: duplicate paths root leaves; second: return list exclusively final number of each path count.
please help! difficult.
i'm not sure trying do, you'll need define recursive function takes node (the head of tree or subtree) , integer (the number of children you've traversed far), , maybe list of each visited node far. if node has no children, you've reached leaf , can print out whatever info need. otherwise, each child, call recursive function again new parameters (+1 count, child node head node, etc).
Comments
Post a Comment