核心:自上而下
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) {}
};
//每次先将 root的左结点->next = root右结点, root右结点->next = root->next的左结点
class Solution {
public:
Node* connect(Node* root) {//自上而下
if (root == NULL || root->left == NULL)
return root;
//根据题意,root如果有左结点就必有右结点
root->left->next = root->right;
if (root->next != NULL)root->right->next = root->next->left;
connect(root->left);
connect(root->right);
return root;
}
};
对于任意一次递归,只考虑如何设置子结点的 next 属性, 分为三种情况:
没有子结点:直接返回
有一个子结点:将这个子结点的 next 属性设置为同层的下一个结点,即为 root->next 的最左边的一个子结点,如果 root->next 没有子结点,则考虑 root->next->next,依次类推
有两个结点:左子结点指向右子结点,然后右子结点同第二种情况的做法
注意递归的顺序需要从右到左
class Solution {
public:
Node* connect(Node* root) {
if (root == NULL)
return NULL;
if (root->left != NULL || root->right != NULL)
{
if (root->left != NULL&&root->right != NULL)
root->left->next = root->right;
Node*child_layer = root->right ? root->right : root->left;
Node*father_layer = root->next;
while (father_layer != NULL&&father_layer->left == NULL&&father_layer->right == NULL)
{
father_layer = father_layer->next;
}
if (father_layer == NULL)
child_layer->next = NULL;
else
child_layer->next = father_layer->left ? father_layer->left : father_layer->right;
connect(root->right);
connect(root->left);
}
return root;
}
};