Flatten Binary Tree to Linked List
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.
Having a deep understanding of pointer and Tree operations, this question is very simple, but not well understood, so it is very difficult.
Important: you cannot change the structure of a tree node that has not been accessed during traversal.
Because of this, this question cannot be written as a normal first-order traversal program.
After careful observation, we will find two features:
1. The modified tree only has the right subtree,
2. The structure of a accessed node can be modified.
Then we can use reverse first-order traversal-because we first access the rightmost right subtree, this right subtree will not be needed in subsequent access, you can change the tree structure.
After thinking about this, this question becomes very simple.
The following two procedures for reverse first-order traversal are very simple:
1.
Void flatten (TreeNode * root) {if (! Root) return; TreeNode * dummy = new TreeNode (-1); flatten (root, dummy); // root = dummy-> right; delete dummy ;} void flatten (TreeNode * root, TreeNode * (& res) {if (! Root) return; flatten (root-> right, res); flatten (root-> left, res); root-> right = res-> right; res-> right = root; root-> left = nullptr ;}
2.
void flatten2(TreeNode *root) {if (!root) return;flatten2(root->right);flatten2(root->left);if (root->left){TreeNode *rMost = root->left;while (rMost->right) rMost = rMost->right;rMost->right = root->right;root->right = root->left;root->left = nullptr;}}