简体   繁体   English

二叉树获取每一层的所有节点

[英]Binary tree get all nodes for every level

I am trying to solve the following, say I have this binary tree...我正在尝试解决以下问题,假设我有这个二叉树......

       3
      / \
     9  20
       /  \
      15   7

Then I need to get all nodes at every level, so my result will be...然后我需要获取每个级别的所有节点,所以我的结果将是......

[[3],[9,20],[15,7]]

I believe I am getting close to a solution, but I'm not sure where I'm going wrong, if someone can help me with my solution that would be great, if I am on the wrong track, please let me know.我相信我正在接近解决方案,但我不确定我哪里出错了,如果有人可以帮助我解决我的解决方案,那会很棒,如果我走错了路,请告诉我。

My first step was to get the depth of the tree using the following function...我的第一步是使用以下 function 获取树的深度...

def get_depth(self, root):
    if root.left == None and root.right == None:
        return 1
    return max(self.get_depth(root.left), self.get_depth(root.right)) + 1

The depth is 3 .深度为3

Next I called a function that was intended to give me the expected result...接下来,我打电话给 function,旨在给我预期的结果......

def levelOrder(self, root):
    depth = self.get_depth(root)
    return self.find_comb(root, [[]]*depth, 0)

def find_comb(self, root, result, level):
    if root is None:
        return None
    self.find_comb(root.left, result, level+1)
    self.find_comb(root.right, result, level+1)
    result[level].append(root.val)
    return result

My thought process was, I would recurse through the tree and the level parameter would keep track of the current level that I am on.我的思考过程是,我将通过树进行递归,并且level参数将跟踪我所在的当前级别。 Then I would append all root.val on that level to the result at that index.然后我会 append 所有root.val在那个级别上到那个索引的结果。

So let's say I am on level 1 (we start at 0), then the nodes at level 1 are 9 and 20 .所以假设我在1级(我们从 0 开始),那么1级的节点是920 So the result would look like [[], [9, 20], [], []] , and it would do this for every level of the tree.所以结果看起来像[[], [9, 20], [], []] ,它会为树的每个级别执行此操作。 I hope my logic is clear.我希望我的逻辑很清楚。 Instead the result I am getting is...相反,我得到的结果是......

[[9, 15, 7, 20, 3], [9, 15, 7, 20, 3], [9, 15, 7, 20, 3]]

You actually don't need to find the depth of the tree. 您实际上不需要找到树的深度。 You just traverse the tree, while keeping the level at which are you, let's say in level variable. 您只需遍历树,同时保持level不变,就可以说是level可变。 And insert your value at listOfLists[level] . 并将您的值插入listOfLists[level] Of course you have to be handle the IndexError: list index out of range . 当然,您必须处理IndexError: list index out of range Here's a simple implementation: 这是一个简单的实现:

def levelTraversal(root, level):
    if root is None:
        return

    if level >= len(listOfLists):
        list = []
        listOfLists.append(list)
    listOfLists[level].append(root.v)
    levelTraversal(root.l, level+1)
    levelTraversal(root.r, level+1)

Call it like this : levelTraversal(rootNode, 0) 像这样调用它: levelTraversal(rootNode, 0)

For your tree the result is : [[3], [9, 20], [15, 7]] 对于您的树,结果为: [[3], [9, 20], [15, 7]]

I don't know Phyton but you might want to look at a BFS implementation on Phyton. 我不认识Phyton,但您可能想看看Phyton上的BFS实现。

https://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/ https://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/

Few improvements and variations from answer of @Schidu Luca @Schidu Luca 的回答几乎没有改进和变化

The problem is the way it was implemented, the child node loses which parent is despite we can retrieve at which level of the tree is.问题在于它的实现方式,尽管我们可以检索树的哪个级别,但子节点会丢失哪个父节点。

Add mapping child -> parent添加映射子 -> 父

nodes = []

def traverse(root, level, parent):
    if not root:
        return
    if level >= len(nodes):
        nodes_level = []
        nodes.append(nodes_level)
    parent_key = parent and parent.value or None
    nodes[level].append({root.value: parent_key})
    traverse(root.left, level + 1, root)
    traverse(root.right, level + 1, root)


traverse(self.root, 0, None)
return nodes

Mapping level -> parent -> childs映射级别 -> 父级 -> 子级

nodes = {}
def traverse_mapped(root, level, parent):
    if not root:
        return
    if level >= len(nodes):
        nodes_level = {}
        nodes[level] = nodes_level
    parent_key = parent and parent.value or None
    if parent_key in nodes[level]:
        nodes[level][parent_key].append(root.value)
    else:
        nodes[level][parent_key] = [root.value]
    traverse_mapped(root.left, level + 1, root)
    traverse_mapped(root.right, level + 1, root)

traverse_mapped(self.root, 0, None)
return nodes

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

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