LeetCode-in-All

114. Flatten Binary Tree to Linked List

Medium

Given the root of a binary tree, flatten the tree into a “linked list”:

Example 1:

Input: root = [1,2,5,3,4,null,6]

Output: [1,null,2,null,3,null,4,null,5,null,6]

Example 2:

Input: root = []

Output: []

Example 3:

Input: root = [0]

Output: [0]

Constraints:

Follow up: Can you flatten the tree in-place (with O(1) extra space)?

Solution

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   int val;
 *   TreeNode? left;
 *   TreeNode? right;
 *   TreeNode([this.val = 0, this.left, this.right]);
 * }
 */
class Solution {
  void flatten(TreeNode? root) {
    if (root != null) {
      _findTail(root);
    }
  }

  TreeNode _findTail(TreeNode root) {
    TreeNode? left = root.left;
    TreeNode? right = root.right;
    TreeNode tail;

    // Find the tail of the left subtree (the leftmost leaf)
    if (left != null) {
      tail = _findTail(left);
      // Stitch the right subtree below the tail
      root.left = null;
      root.right = left;
      tail.right = right;
    } else {
      tail = root;
    }

    // Find the tail of the right subtree
    if (tail.right == null) {
      return tail;
    } else {
      return _findTail(tail.right!);
    }
  }
}