题目描述
解法:
先用递归解一下,我们的做法是将每两个相邻的结点都连接起来,那就是 n o d e 1. l e f t → n o d e 1. r i g h t node1.left\rightarrow node1.right node1.left→node1.right , n o d e 2. l e f t → n o d e 2. r i g h t node2.left\rightarrow node2.right node2.left→node2.right, n o d e 1. r i g h t → n o d e 2. l e f t node1.right\rightarrow node2.left node1.right→node2.left
/*
// 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) {
if (root == nullptr) return root;
connectTwoNode(root->left, root->right);
return root;
}
void connectTwoNode(Node* node1, Node* node2){
if (node1 == nullptr || node2 == nullptr) return;
node1->next = node2;
connectTwoNode(node1->left, node1->right);
connectTwoNode(node2->left, node2->right);
connectTwoNode(node1->right, node2->left);
}
};