114. Flatten Binary Tree to Linked List

2019/10/14 Leetcode

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

Solution

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


// straight
// O(n^2) NOT GOOD ENOUGH
// Right -> Left -> Root
class Solution {
    public void flatten(TreeNode root) {
        if (root == null) return;
        TreeNode left = root.left, right = root.right;
        root.left = null;
        flatten(left);
        flatten(right);
        root.right = left;
        
        TreeNode curr = root;
        while (curr.right != null) {
            curr = curr.right;
        }
        
        curr.right = right;   
    }
}

Search

    Table of Contents