一:题目
二:上码
/*
// 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) {/**思路:虽然很明显这道题是用层序遍历,但是没太理解题意,看了题解才明白,这是在原来的二叉树上做些操作,我们需要是将每层的结点用next指针连起来,这个操作在我们遍历每层结点可以操作**/queue<Node*>q;if(root) q.push(root);while(!q.empty()) {int size = q.size();Node* head; Node* node;for(int i = 0; i < size; i++) {if(i == 0) {head = q.front();//这是头结点q.pop();node = head;//处理其结点的孩子节点}else{node = q.front();//这是头结点的后续结点q.pop();head->next = node;head = head->next;}if(node->left) q.push(node->left);if(node->right) q.push(node->right);}head->next = NULL;//最后的指针指向空}return root;}
};