简体   繁体   English

n叉树中BFS的复杂度

[英]Complexity of BFS in n-ary tree

I am looking for algorithm to do BFS in O(n) for n-ary tree, I found the following algorithm, but I have a problem in analysing the time complexity.我正在寻找在 O(n) 中为 n 叉树执行 BFS 的算法,我找到了以下算法,但我在分析时间复杂度时遇到了问题。 I am not sure if it's O(n) or O(n^2).我不确定它是 O(n) 还是 O(n^2)。 Can someone explain the time complexity or give an alternative algorithm which run in O(n)有人可以解释时间复杂度或给出一个在 O(n) 中运行的替代算法

Thanks谢谢

breadthFirstSearch = (root, output = []) => {
  if (!root) return output;
  const q = new Queue();
  q.enqueue(root);
  while (!q.isEmpty()) {

    const node = q.dequeue();
    
    output.push(node.val);
    
    for (let child of node.children) {
      q.enqueue(child);
    }
  }
  return output;
};

That is indeed a BFS algorithm for a generic tree.这确实是通用树的 BFS 算法。 If you define as the in -ary tree, then the time complexity is not related to that.如果你定义为 in -ary 树,那么时间复杂度与它无关。

If however, represents the total number of nodes in the tree, then the time complexity is O() because every node is enqueued exactly once, and dequeued exactly once.但是,如果 表示树中的节点总数,则时间复杂度为 O(),因为每个节点恰好入队一次,并且恰好出队一次。 As queue operations are O(1), the time complexity is O().由于队列操作是O(1),所以时间复杂度是O()。

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

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