法一:
/*
// 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){deque<Node*> queue;if (root == nullptr) return root;queue.push_back(root);root->next = nullptr;//处理的是当前节点的下一层while (!queue.empty()){int size = queue.size();Node* leftSideNode = NULL;for (int i = 0; i < size; i++){Node* parent = queue.front();queue.pop_front();//已经处于叶子节点层if (parent->left == nullptr) return root;//未处于叶子结点层queue.push_back(parent->left);queue.push_back(parent->right);//连接if (i == size - 1) //此层最右侧{ parent->left->next = parent->right;parent->right->next == nullptr;if (leftSideNode != nullptr){leftSideNode->next = parent->left;}break;}else if (i == 0 && leftSideNode == NULL) //此层起始处 {parent->left->next = parent->right;leftSideNode = parent->right;}else{parent->left->next = parent->right;leftSideNode->next = parent->left;leftSideNode = parent->right;}}}return root;}
};
法二:
class Solution {
public:Node* connect(Node* root) { deque<Node*> queue;if (root == NULL) return root;queue.push_back(root);while (!queue.empty()){int size = queue.size();for (int i = 0; i < size; i++){ Node* node = queue.front();queue.pop_front();//连接if (i < size - 1){node->next = queue.front();}elsenode->next = nullptr;//左孩子为空,说明是叶子结点了(题目给定满二叉树)if (node->left != nullptr) {queue.push_back(node->left);queue.push_back(node->right);}}}return root;}
};