image.png

思路:

  1. 层次遍历二叉树
  2. 每一层都进行“将数组内部用指针连接起来”的操作

    代码:

    ```cpp / // 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)

    1. : val(_val), left(_left), right(_right), next(_next) {}

    }; */

class Solution { public: void levelConnect(vector &nodes, int nodes_size) { for (int i = 0; i < nodes_size - 1; ++i) { nodes[i]->next = nodes[i + 1]; } nodes[nodes_size - 1]->next = NULL; }

Node* connect(Node* root) {
    if (!root) {
        return root;
    }

    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        vector<Node*> nodes;
        int cur_level_size = q.size();
        for (int i = 0; i < cur_level_size; ++i) {
            Node* cur_node = q.front();
            q.pop();
            nodes.push_back(cur_node);

            if(cur_node->left) q.push(cur_node->left);
            if(cur_node->right) q.push(cur_node->right);
        }
        levelConnect(nodes, cur_level_size);
    }

    return root;
}

}; ```