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 }