Solving Flatten Binary Tree to Linked List in go. Please try yourself first to solve the problem and submit your implementation to LeetCode before looking into solution.

Problem Description

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

            1
       / \
      2   5
     / \   \
    3   4   6
    -----------        
    pre = 5
    cur = 4

        1
       / 
      2   
     / \   
    3   4
         \
          5
           \
            6
    -----------        
    pre = 4
    cur = 3

        1
       / 
      2   
     /   
    3 
     \
      4
       \
        5
         \
          6
    -----------        
    cur = 2
    pre = 3

        1
       / 
      2   
       \
        3 
         \
          4
           \
            5
             \
              6
    -----------        
    cur = 1
    pre = 2

    1
     \
      2
       \
        3
         \
          4
           \
            5
             \
              6

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

    private TreeNode prev = null;

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

See the full details of the problem Flatten Binary Tree to Linked List at LeetCode

Originally posted at: @github.com/halfrost/LeetCode-Go