Flatten Binary Tree to Linked List
Problem Description:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree shoshould look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
Click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Train of Thought 1: Start from the root node according to the meaning of the question. If the current node has a left child, add its left child to itself and the right child, locate the rightmost node of the left child and connect it to the current right child. Then, process the right child in sequence until the right child is empty. The Code is as follows:
/*** Definition for binary tree * struct TreeNode {* int val; * TreeNode * left; * TreeNode * right; * TreeNode (int x): val (x ), left (NULL), right (NULL) {}*}; */class Solution {public: void flatten (TreeNode * root) {if (root = NULL) return; while (root! = NULL) {if (root-> left! = NULL) {TreeNode * p = root-> left; while (p-> right! = NULL) // find the rightmost node of the left child {p = p-> right;} p-> right = root-> right; root-> right = root-> left; root-> left = NULL;} root = root-> right ;}}};
Train of Thought 2: we can see that the transformed tree is actually arranged in the order of first-order traversal. Therefore, we can use the Middle-order recursive traversal to record the first-order traversal node, adjust the left and right subtree of each child in sequence. Note that during the traversal process, you must first record the right subtree of the current node, and then adjust the left and right subtree of the current node, then recursively adjust the left and right subtree. The Code is as follows:
/*** Definition for binary tree * struct TreeNode {* int val; * TreeNode * left; * TreeNode * right; * TreeNode (int x): val (x ), left (NULL), right (NULL) {}*}; */class Solution {public: TreeNode * pre = NULL; void flatten (TreeNode * root) {if (root = NULL) return; TreeNode * lastright = root-> right; // record the right subtree of the current node if (pre) {pre-> left = NULL; pre-> right = root;} pre = root; flatten (root-> left); flatten (lastright );}};