题解
这题把示例的图 转一下 因为不需要考虑pre指针 发现其实是一颗二叉树 只要先序遍历节点就行
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
class Solution {
public:
void preOrder(Node* node, vector<Node*> &res) {
if(!node) return;
res.push_back(node);
preOrder(node->child, res);
preOrder(node->next, res);
}
Node* flatten(Node* head) {
if(!head) return head;
vector<Node*> res;
preOrder(head, res);
head = res[0];
head->child = nullptr;
head->next = nullptr;
Node *p = head;
for(int i=1; i<res.size(); i++) {
Node *q = res[i];
q->prev = p;
q->next = p->next;
q->child = nullptr;
p->next = q;
p = p->next;
}
return head;
}
};