LeetCode Solutions
114. Flatten Binary Tree to Linked List
Time: $O(n)$ Space: $O(h)$
class Solution {
public:
void flatten(TreeNode* root) {
if (root == nullptr)
return;
flatten(root->left);
flatten(root->right);
TreeNode* const left = root->left; // Flattened left
TreeNode* const right = root->right; // Flattened right
root->left = nullptr;
root->right = left;
// Connect the original right subtree
// To the end of new right subtree
TreeNode* rightmost = root;
while (rightmost->right)
rightmost = rightmost->right;
rightmost->right = right;
}
};
class Solution {
public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.left);
flatten(root.right);
TreeNode left = root.left; // Flattened left
TreeNode right = root.right; // Flattened right
root.left = null;
root.right = left;
// Connect the original right subtree
// To the end of new right subtree
TreeNode rightmost = root;
while (rightmost.right != null)
rightmost = rightmost.right;
rightmost.right = right;
}
}
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
if not root:
return
self.flatten(root.left)
self.flatten(root.right)
left = root.left # Flattened left
right = root.right # Flattened right
root.left = None
root.right = left
# Connect the original right subtree
# To the end of new right subtree
rightmost = root
while rightmost.right:
rightmost = rightmost.right
rightmost.right = right