简体   繁体   English

非二叉树python中的顺序

[英]inorder in non binary tree python

我想在 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.您的代码不包括所有子节点,因为您专门从first_halfsecond_half列表中选择一个节点来递归并忽略其他所有内容。 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.实际上,对于某些类型的非二叉树(如 B 树),树的每个节点中存储有多个值,并且适当的中序遍历会将它们交错在子节点的值之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM