LeetCode 116. Populating Next Right Pointers in Each Node
2014-08-08 06:55
417 查看
和LeetCode 102. Binary Tree Level Order Traversal差不多个意思。
用q维护同一高度的节点,先进先出进行操作即可。
代码:
class Solution
{
public:
void connect(TreeLinkNode *root)
{
queue<TreeLinkNode*> nodes;
queue<TreeLinkNode*> children;
nodes.push(root);
nodes.push(NULL);
while ( nodes.front() != NULL )
{
auto cur = nodes.front();
nodes.pop();
cur->next = nodes.front();
if (cur->left != NULL)
{
children.push( cur->left );
}
if (cur->right != NULL)
{
children.push( cur->right );
}
if (nodes.front() == NULL)
{
nodes = children;
nodes.push(NULL);
while (children.empty() == false)
{
children.pop();
}
}
}
}
};
用q维护同一高度的节点,先进先出进行操作即可。
代码:
class Solution
{
public:
void connect(TreeLinkNode *root)
{
queue<TreeLinkNode*> nodes;
queue<TreeLinkNode*> children;
nodes.push(root);
nodes.push(NULL);
while ( nodes.front() != NULL )
{
auto cur = nodes.front();
nodes.pop();
cur->next = nodes.front();
if (cur->left != NULL)
{
children.push( cur->left );
}
if (cur->right != NULL)
{
children.push( cur->right );
}
if (nodes.front() == NULL)
{
nodes = children;
nodes.push(NULL);
while (children.empty() == false)
{
children.pop();
}
}
}
}
};
相关文章推荐
- leetcode_question_116 Populating Next Right Pointers in Each Node
- [LeetCode]116.Populating Next Right Pointers in Each Node
- Leetcode 116 Populating Next Right Pointers in Each Node 二叉树填充next指针指向右侧结点
- Leetcode #116 Populating Next Right Pointers in Each Node
- [Leetcode 116, Medium] Populating Next Right Pointers in Each Node
- LeetCode 116 Populating Next Right Pointers in Each Node
- LeetCode 116. Populating Next Right Pointers in Each Node
- leetcode-116-Populating Next Right Pointers in Each Node
- Java for LeetCode 116 Populating Next Right Pointers in Each Node
- [LeetCode 116 117] - 填充每一个节点的指向右边邻居的指针I & II (Populating Next Right Pointers in Each Node I & II)
- Leetcode 笔记 116 - Populating Next Right Pointers in Each Node
- LeetCode 116 Populating Next Right Pointers in Each Node 解题报告
- Populating Next Right Pointers in Each Node - LeetCode 116
- leetcode 116 —— Populating Next Right Pointers in Each Node
- [LeetCode]116 Populating Next Right Pointers in Each Node
- LeetCode(116) Populating Next Right Pointers in Each Node
- Leetcode_116_Populating Next Right Pointers in Each Node
- leetcode[116]Populating Next Right Pointers in Each Node
- leetcode[116]:Populating Next Right Pointers in Each Node
- leetcode || 116、Populating Next Right Pointers in Each Node