我想在 python 中构建一个函数,它获取一些非二叉树并将树中的值从左到右按顺序放在列表中。
Your code isn't including all the child nodes because you're specifically picking out just one node from your first_half
and second_half
lists to recurse on and ignoring everything else. Probably you want to loop over each of those lists instead:
mid = int(len(children) / 2) + 1
first_half = children[:mid]
second_half = children[mid:]
for child in first_half:
child.iters(by_order)
by_order.append(self)
for child in second_half
child.iters(by_order)
It's worth noting that this order seems a bit awkward. You're choosing to stick the parent node in the exact middle of its children (or as close as possible, for odd-numbers of children), but that is a bit arbitrary. While the child nodes have a definitive order, there's not necessarily a clear reason to order the parent in any particular relation to them. Indeed, for some kinds of non-binary trees (like B-trees), there are multiple values stored in each node of the tree, and a proper in-order traversal would interleave them in between the child nodes' values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.