114. Flatten Binary Tree to Linked List
Problem
Flatten a binary tree in place into a "linked list" that follows preorder: each node's right points to the next node in preorder and every left is null.
Example: [1,2,5,3,4,null,6] → 1 → 2 → 3 → 4 → 5 → 6 along right pointers
Constraints: follow-up: O(1) extra space.
For each node with a left child: find the rightmost node of the left subtree, hook the right subtree there, move left to right. Walk right. O(1) space (Morris-style).
1 1
/ \ \
2 5 -> 2
/ \ \ \
3 4 6 3 - 4 - 5 - 6
Complexity: O(n) time, O(1) space.
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
cur = root
while cur:
if cur.left:
p = cur.left
while p.right:
p = p.right
p.right = cur.right
cur.right, cur.left = cur.left, None
cur = cur.right
t = make_tree([1, 2, 5, 3, 4, None, 6]); Solution().flatten(t)
assert tree_vals(t) == [1, None, 2, None, 3, None, 4, None, 5, None, 6]
t = make_tree([0]); Solution().flatten(t)
assert tree_vals(t) == [0]
assert Solution().flatten(None) is None
class Solution {
public void flatten(TreeNode root) {
for (TreeNode cur = root; cur != null; cur = cur.right) {
if (cur.left != null) {
TreeNode p = cur.left;
while (p.right != null) p = p.right;
p.right = cur.right;
cur.right = cur.left;
cur.left = null;
}
}
}
}
func flatten(root *TreeNode) {
for cur := root; cur != nil; cur = cur.Right {
if cur.Left != nil {
p := cur.Left // rightmost node of the left subtree
for p.Right != nil {
p = p.Right
}
p.Right = cur.Right
cur.Right, cur.Left = cur.Left, nil
}
}
}