Leetcode 之Populating Next Right Pointers in Each Node II(51)
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; } }