Flatten Binary Tree to Linked List (Medium-Difficulty)

Problem is here: https://leetcode.com/problems/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

The interesting aspect of this problem is that you cannot create a separate structure to accommodate the flatten list - rather, you're supposed to change the current Tree.
In order to do that, what I did was the following:

1) Step one was to make a copy of the initial tree. This sub-problem looks relatively easy, but you should try it, it actually has some nuances worth checking
2) Once with the copy of the tree, you can do a pre-order traversal using the copy and then assign to the root tree appropriately

It did the trick. Cheers, ACC.


public class Solution
{
    public void Flatten(TreeNode root)
    {
        TreeNode copy = null;
        TreeNode anchor = null;
        CopyTree(root, false, ref copy, ref anchor);
        Flatten(anchor, true, ref root);
    }

    private void CopyTree(TreeNode treeFrom,
                            bool leftChild,
                            ref TreeNode treeTo,
                            ref TreeNode anchor)
    {
        if (treeFrom == null) return;
        if (treeTo == null)
        {
            treeTo = new TreeNode(treeFrom.val);
            anchor = treeTo;
        }
        else
        {
            if (leftChild)
            {
                treeTo.left = new TreeNode(treeFrom.val);
                treeTo = treeTo.left;
            }
            else
            {
                treeTo.right = new TreeNode(treeFrom.val);
                treeTo = treeTo.right;
            }
        }
        CopyTree(treeFrom.left, true, ref treeTo, ref anchor);
        CopyTree(treeFrom.right, false, ref treeTo, ref anchor);
    }

    private void Flatten(TreeNode copy,
                            bool first,
                            ref TreeNode root)
    {
        if (copy == null) return;

        if (first)
        {
            root.val = copy.val;
            root.left = null;
        }
        else
        {
            root.right = new TreeNode(copy.val);
            root.left = null;
            root = root.right;
        }
        Flatten(copy.left, false, ref root);
        Flatten(copy.right, false, ref root);
    }

    public void Print(TreeNode node, string label)
    {
        if (node == null) return;
        Console.WriteLine("{0}: {1}", label, node.val);
        Print(node.left, "left");
        Print(node.right, "right");
    }
}

Comments

Popular posts from this blog

Golang vs. C#: performance characteristics (simple case study)

Claude vs ChatGPT: A Coder's Perspective on LLM Performance

ProjectEuler Problem 719 (some hints, but no spoilers)