void connect(TreeLinkNode *root)
{
while (root)
{
//每一层循环时重新初始化
TreeLinkNode *prev = nullptr;
TreeLinkNode *next = nullptr;
//对于每一层
for (; root; root = root->next)
{
//每一层开始时,记录下一层的起始结点
if (!next)next = root->left ? root->left : root->right; if (root->left)
{
//如果不是起始结点,则将prev与该左子结点相连接
if (prev)prev->next = root->left;
//如果是每层的起始结点,则将左子结点直接赋给prev
prev = root->left;
}
if (root->right)
{
if (prev)prev->next = root->right;
prev = root->right;
}
}
root = next;
}
}
相关文章
- Leetcode 之Populating Next Right Pointers in Each Node II(51)
- leetcode—Populating Next Right Pointers in Each Node
- leetcode第一刷_Populating Next Right Pointers in Each Node II
- [LeetCode]题解(python):117-Populating Next Right Pointers in Each Node II
- 【LeetCode OJ】Populating Next Right Pointers in Each Node II
- 【一天一道LeetCode】#116. Populating Next Right Pointers in Each Node
- leetcode 199. Binary Tree Right Side View 、leetcode 116. Populating Next Right Pointers in Each Node 、117. Populating Next Right Pointers in Each Node II
- [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