A "binary tree middle order traversal problem", which is unfamiliar to binary tree middle order traversal, I suggest moving first Middle order traversal of LeetCode94 binary tree.
Question 94 is to output node values in the form of an array in the order of traversal in the middle order. The difference in this problem is that it is necessary to build a circular two-way linked list structure. The left pointer is equivalent to the prev pointer, and the right pointer is equivalent to the next pointer. In addition, the head and tail should be connected (record the head and tail, and finally connect them).
Therefore, the task to be completed in the step of adding the node val value to the array becomes: the current node is marked as a, A.left = the last added node B (if not null), B.right = a; = > Thus, it is analyzed that the previous node needs to be recorded (just in line with the meaning of the node recorded by the tail pointer). When processing a, A.left, that is, its left subtree has been processed, so the left pointer can be changed, but the right subtree will be traversed after a (the nature of binary search tree), so the right pointer can only be changed when processing the next node.
In addition, pay special attention to the empty tree when connecting end to end.
Solution 1: recursion
Solution 2: stack
Recursion implicitly calls the stack. Similarly, we can imitate the recursion order and explicitly present the stack: the recursion order is to find the left subtree first. If the left subtree is empty, return to the root node. After the root node is processed, process the right subtree of the root node, and return to the root node of a higher level after the right subtree is processed.
So the problem is that we need to record the parent node: otherwise we can't return! This is what the recursive stack does. Next, we directly use stack to complete this function, and the processing order is to first process the low-level root node and then the high-level root node, which is just in line with the characteristics of stack first in and then out.
Solution 3: order traversal in Morris
Note that the order of operations 1 and 2 in the code comments cannot be exchanged: at this time, the predecessor is the precursor node of root (tail points to the predecessor). When calling visit, the right pointer of the precursor node will point to root. If you change the predecessor.right to null after visit, it is equivalent to disconnecting the connection again.