/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ #include <cstddef> #include <queue> class Solution { public: void connect(TreeLinkNode* root) { if (root == nullptr) return ; queue<TreeLinkNode*> qu; queue<TreeLinkNode*> jl; qu.push(root); bool hou = false; while (qu.size() > 0 || jl.size() > 0) { if (hou == false) { TreeLinkNode* t; t = qu.front(); qu.pop(); if (qu.size() == 0) { t->next = nullptr; hou = true; } else t->next = qu.front(); if (t->left != nullptr) { jl.push(t->left); } if (t->right != nullptr) { jl.push(t->right); } } else { TreeLinkNode* t; t = jl.front(); jl.pop(); if (jl.size() == 0) { t->next = nullptr; hou = false; } else t->next = jl.front(); if (t->left != nullptr) { qu.push(t->left); } if (t->right != nullptr) { qu.push(t->right); } } } } };