简体   繁体   English

如何使用bfs查找n元树的最大深度?

[英]How to find max depth of n-ary tree using bfs?

This is my node definition : 这是我的节点定义:

class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children

Now I've to find max depth in the tree. 现在,我必须在树中找到最大深度。 I'm using breadth-first search to mark the level of each node, then returning the max of levels. 我正在使用广度优先搜索来标记每个节点的级别,然后返回级别的最大值。

This is my code : 这是我的代码:

def maxDepth(self, root):
    """
    :type root: Node
    :rtype: int
    """
    if(root == None):
        return 0

    q = []
    q.append(root)

    level={root.val:1}

    while(len(q)>0):

        s = q.pop(0)

        for c in s.children:
            q.append(c)
            level[c.val]=level[s.val]+1

    return max(level.values())

It's working on some cases but giving the wrong answer in many cases. 它在某些情况下有效,但在许多情况下给出错误的答案。 I don't understand where I'm missing the concept? 我不明白我在哪里缺少这个概念?

正如@pfctgeorge所建议的那样,我是根据节点值附加级别的,但是可能有多个具有相同值的节点,因为它是一棵树,在这种情况下会给出错误的答案。

Since you know where you went wrong, you could do something like below to achieve max depth of the tree- 既然您知道哪里出了问题,您可以执行以下类似操作以达到树的最大深度-

Pseudocode: 伪代码:

q = []
q.offer(root)
level = 1

while q.isEmpty() == false:

    size = q.size()
    for i = 0 to size:
        curr_node = q.poll()
        for each_child in curr_node:
            q.offer(each_child)

    level = level + 1

return level

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

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