思路:对整个满二叉树进行层次遍历,同时把每一层的节点连起来now->next=q.front()
,当到达该层最后一个结点时(len-1
)时,令其指向NULL;
/* // Definition for a Node. class Node { public:int val;Node* left;Node* right;Node* next;Node() : val(0), left(NULL), right(NULL), next(NULL) {}Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}Node(int _val, Node* _left, Node* _right, Node* _next): val(_val), left(_left), right(_right), next(_next) {} }; */class Solution {
public:Node *connect(Node *root){
//层次遍历queue<Node *> q;if (root == nullptr)return NULL;int len = 1;q.push(root);while (!q.empty()){
for (int i = 0; i < len; i++){
Node *now = q.front();q.pop();if (i == len - 1) //该层最后一个节点{
now->next = NULL;}else{
now->next = q.front();}//如果当前节点有孩子节点,则放入队列中(对于完美二叉树,有一个孩子节点=>有两个孩子节点)if (now->left){
q.push(now->left);}if (now->right){
q.push(now->right);}}len *= 2;}return root;}
};