Leetcode 114. Flatten Binary Tree to Linked List
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
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {};
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {};
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {};
};
To flatten the binary tree into a linked list:
nullptr
.Both recursive and iterative methods will be discussed, but let’s proceed with the recursive implementation.
Here is the C++ code for the recursive solution:
class Solution {
public:
void flatten(TreeNode* root) {
// Base case: if the tree is empty or it is a leaf node, return
if (root == nullptr || (root->left == nullptr && root->right == nullptr)) {
return;
}
// Flatten the left subtree
if (root->left != nullptr) {
flatten(root->left);
// Temporarily store the right subtree
TreeNode* tempRight = root->right;
// Move the left subtree to the right
root->right = root->left;
root->left = nullptr;
// Find the rightmost node of the moved subtree
TreeNode* t = root->right;
while (t->right != nullptr) {
t = t->right;
}
// Attach the temporarily stored right subtree
t->right = tempRight;
}
// Flatten the right subtree
flatten(root->right);
}
};
The time complexity of this solution is O(n), where n is the number of nodes in the tree. This is because each node is visited once during the traversal in the recursive calls.
The space complexity is O(h) where h is the height of the tree, which corresponds to the space used by the system’s call stack during the recursive calls. In the worst case, for a completely unbalanced tree, this can be O(n), but on average for a balanced tree, it would be O(log n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?