Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
把左邊的節點一個一個搬到右邊的subtree上。
// Iteration
void flatten(TreeNode* root) { // time: O(n); space: O(1)
TreeNode* cur = root;
while (cur) {
if (cur->left) {
TreeNode* pre = cur->left;
// Find the prenode of the current node
while (pre->right) {
pre = pre->right;
}
// Link the prenode to the current node's right subtree
pre->right = cur->right;
// Replace the current node's right subtree with the current node's left subtree
cur->right = cur->left;
cur->left = nullptr;
}
cur = cur->right;
}
}