原题地址

 

二叉树的层次遍历。

对于每一层,依次把各节点连起来即可。

 

代码:

 1 void connect(TreeLinkNode *root) {
 2   if (!root) return;
 3 
 4   queue<TreeLinkNode *> parents;
 5 
 6   parents.push(root);
 7   while (!parents.empty()) {
 8     queue<TreeLinkNode *> children;
 9 
10     while (!parents.empty()) {
11       TreeLinkNode *p = parents.front();
12       parents.pop();
13       p->next = parents.empty() ? NULL : parents.front();
14       if (p->left)
15         children.push(p->left);
16       if (p->right)
17         children.push(p->right);
18     }
19     parents = children;
20   }
21 }

 

相关文章:

  • 2021-10-11
  • 2021-09-01
  • 2021-09-13
  • 2021-08-22
  • 2021-12-24
  • 2021-11-23
猜你喜欢
  • 2021-04-01
  • 2021-04-13
  • 2021-11-07
  • 2021-05-27
  • 2021-09-15
  • 2022-01-11
相关资源
相似解决方案