Leetcode 114. Flatten Binary Tree to Linked List
Given the root of a binary tree, flatten the tree into a “linked list”:
Input: root = [1, 2, 5, 3, 4, null, 6]
Output: [1, null, 2, null, 3, null, 4, null, 5, null, 6]
root
is null
)?
null
.public class Solution {
public void flatten(TreeNode root) {
flattenTree(root);
}
private TreeNode flattenTree(TreeNode node) {
// Base case: if the node is null, return null
if (node == null) return null;
// If the node is a leaf, return the node itself
if (node.left == null && node.right == null) return node;
// Recursively flatten the left and right subtrees
TreeNode leftTail = flattenTree(node.left);
TreeNode rightTail = flattenTree(node.right);
// If there was a left subtree, we shuffle the connections
if (leftTail != null) {
leftTail.right = node.right;
node.right = node.left;
node.left = null;
}
// The new tail is the rightmost of the right subtree
return rightTail != null ? rightTail : leftTail;
}
}
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?