Leetcode#117 Populating Next Right Pointers in Each Node II

原题地址

 

二叉树的层次遍历。

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

 

代码:

复制代码
 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 }
复制代码

 

posted @   李舜阳  阅读(326)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示