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

把左邊的節點一個一個搬到右邊的subtree上。

// Iteration
void flatten(TreeNode* root) { // time: O(n); space: O(1)
    TreeNode* cur = root;
    while (cur) {
        if (cur->left) {
            TreeNode* pre = cur->left;
            // Find the prenode of the current node
            while (pre->right) {
                pre = pre->right;
            }
            // Link the prenode to the current node's right subtree
            pre->right = cur->right;
            // Replace the current node's right subtree with the current node's left subtree
            cur->right = cur->left;
            cur->left = nullptr;
        }
        cur = cur->right;
    }
}
// Recursion
void helper(TreeNode* root, TreeNode*& prev) {
    if (!root) return;
    helper(root->right, prev);
    helper(root->left, prev);
    root->right = prev;
    root->left = nullptr;
    prev = root;
}
void flatten(TreeNode* root) { // time: O(n); space: O(n)
    TreeNode* prev = nullptr;
    helper(root, prev);
}

Last updated

Was this helpful?