KatInterview

114. Flatten Binary Tree to Linked List

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to flatten a binary tree into a linked list structure in-place. The resulting "linked list" should use the TreeNode class, where the right child pointer acts as the next pointer, and the left child pointer is always null. The order of nodes in the list must correspond to a pre-order traversal of the original tree.

Solution

Flatten Binary Tree to Linked List in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        current = root
        while current:
            if current.left:
                # Find the rightmost node of the left subtree.
                predecessor = current.left
                while predecessor.right:
                    predecessor = predecessor.right
                
                # Rewire the connections:
                # 1. Connect the predecessor's right to the current node's right subtree.
                predecessor.right = current.right
                
                # 2. Move the left subtree to the right side.
                current.right = current.left
                
                # 3. Set the left subtree to None.
                current.left = None
            
            # Move to the next node in the flattened structure.
            current = current.right

Flatten Binary Tree to Linked List in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        TreeNode current = root;
        while (current != null) {
            if (current.left != null) {
                // Find the rightmost node of the left subtree.
                TreeNode predecessor = current.left;
                while (predecessor.right != null) {
                    predecessor = predecessor.right;
                }

                // Rewire the connections:
                // 1. Connect the predecessor's right to the current node's right subtree.
                predecessor.right = current.right;

                // 2. Move the left subtree to the right side.
                current.right = current.left;

                // 3. Set the left subtree to null.
                current.left = null;
            }
            
            // Move to the next node in the flattened structure.
            current = current.right;
        }
    }
}

Flatten Binary Tree to Linked List in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        TreeNode* current = root;
        while (current) {
            if (current->left) {
                // Find the rightmost node of the left subtree
                TreeNode* predecessor = current->left;
                while (predecessor->right) {
                    predecessor = predecessor->right;
                }
                
                // Rewire the connections:
                // 1. Connect the predecessor's right to the current node's right subtree.
                predecessor->right = current->right;
                
                // 2. Move the left subtree to the right side.
                current->right = current->left;
                
                // 3. Set the left subtree to null.
                current->left = nullptr;
            }
            
            // Move to the next node in the flattened structure.
            current = current->right;
        }
    }
};

Flatten Binary Tree to Linked List in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 Do not return anything, modify root in-place instead.
 */
function flatten(root: TreeNode | null): void {
    let current = root;
    while (current) {
        if (current.left) {
            // Find the rightmost node of the left subtree.
            let predecessor = current.left;
            while (predecessor.right) {
                predecessor = predecessor.right;
            }

            // Rewire the connections:
            // 1. Connect the predecessor's right to the current node's right subtree.
            predecessor.right = current.right;

            // 2. Move the left subtree to the right side.
            current.right = current.left;

            // 3. Set the left subtree to null.
            current.left = null;
        }

        // Move to the next node in the flattened structure.
        current = current.right;
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.