Requirements: Given A binary tree, flatten it to a linked list in-place. The tree that transforms the two fork into a flat sequence. Like what:
The idea of knot problem:
The question has a hint that the sequence of the transformed tree is exactly the sequence of the two-fork-tree pre-sequence traversal, so the first idea of the problem is to make use of the way of the pre-order traversal.
The second idea: we can use the idea of recursion, first to the root node processing, the root of the left subtree to the right subtree, in the left subtree in the right end of the node "grafted" to the right subtree, and then the above-obtained sub-tree. Next, the next node of the current binary tree is processed in the same way. Look at the following diagram to be clear.
I realized the second way of thinking, the code is as follows:
1 structTreeNode {2 intVal;3treenode*Left ;4treenode*Right ;5TreeNode (intx): Val (x), left (null), right (null) {}6 };7 8 voidFlatten (TreeNode *root)9 {Ten if(NULL = =root) One return; A //using a non-recursive method of stack -TreeNode *left = root->Left ; -TreeNode *right = root->Right ; the - if(left) { -Root->right =Left ; -Root->left =NULL; + -TreeNode *ptemp =Left ; + while(ptemp->Right ) APtemp = ptemp->Right ; atPtemp->right =Right ; - -Flatten (root->Right ); - } -}
Leetcode:flatten Binary Tree to Linked List