114. Flatten Binary Tree to Linked List

Question

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6

The flattened tree should look like:

   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

Quick Hints

  • Postorder traversal
  • right and then left

Solution

Initial solution:
  • I was able to implement this solution which passed leetcode OJ. Although, this is not efficient
class Solution {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        flatten(root.left);
        flatten(root.right);
        if (root.left != null) {
            TreeNode target = root.left;
            while (target.right != null) {
                target = target.right;
            }
            target.right = root.right;
            root.right = root.left;
            root.left = null;
        }
    }
}
Optimal Solution:
  • The optimal way to solve this is to do postorder traversal visiting the right node followed by the left.

Time complexity

O (n)

Space complexity

O(1) except the space on stack

Notes