Easy Understand Java Recursive solution beat 100% with Explanation
The idea is simple. We always keep a pre global variable to keep track of the last node we visited and connect current node head with this pre node. So for each
The idea is simple. We always keep a `pre` global variable to keep track of the last node we visited and connect current node `head` with this `pre` node. So for each recursive call, we do \n- Connect last visited node with current node by letting `pre.next` point to current node `head` and current node\'s `prev` point to `pre`\n- Mark current node as pre. `pre = head`\n- If there is `head.child`, we recursively visit and flatten its child node \n- Recursively visit and flatten its next node \n```java\nclass Solution {\n/*Global variable pre to track the last node we visited */\n    Node pre = null;\n    public Node flatten(Node head) {\n        if (head == null) {\n            return null; \n        }\n/*Connect last visted node with current node */\n        if (pre != null) {\n            pre.next = head; \n            head.prev = pre;\n        }\n\n        pre = head; \n/*Store head.next in a next pointer in case recursive call to flatten head.child overrides head.next*/\n        Node next = head.next; \n\n        flatten(head.child);\n        head.child = null;\n\n        flatten(next);        \n        return head; \n    }\n}\n```
[]