DEV Community

Wenqi Jiang
Wenqi Jiang

Posted on

114. Flatten Binary Tree to Linked List

Description

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

  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.

Example 1:

Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: root = []
Output: []
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: root = [0]
Output: [0]
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • 100 <= Node.val <= 100

Solutions

Solution 1

Intuition

Code

public void flatten(TreeNode root) {
    if (root == null) {
        return;
    }
    Stack<TreeNode> nodes = new Stack<>();
    nodes.push(root);
    while (!nodes.isEmpty()) {
        TreeNode node = nodes.pop();
        if (node.right != null) {
            nodes.push(node.right);
        }
        if (node.left != null) {
            nodes.push(node.left);
        }
        node.left = null;
        if (!nodes.isEmpty()) {
            node.right = nodes.peek();
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n^2)
  • Space: O(n)

Solution 2

Intuition

Code

public void flatten(TreeNode root) {
    if (root == null) {
        return;
    }
    TreeNode left = root.left, right = root.right;
    root.left = null;
    root.right = left;
    flatten(left);
    flatten(right);

    TreeNode cur = root;
    while (cur.right != null) {
        cur = cur.right;
    }
    cur.right = right;
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(N^2)
  • Space: O(N)

Solution 3

public void flatten(TreeNode root) {
    TreeNode curr = root;
    while (curr != null) {
        if (curr.left != null) {
            TreeNode prev = curr.left;
            while (prev.right != null) {
                prev = prev.right;
            }
            prev.right = curr.right;
            curr.right = curr.left;
            curr.left = null;
        }
        curr = curr.right;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)