https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
Please comment on performance
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
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
[TestClass]
public class FlattenBinaryTree2LinkedList
{
[TestMethod]
public void FlattenBinaryTree2LinkedListTest()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(5);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
root.right.right = new TreeNode(6);
Flatten(root);
Assert.AreEqual(1, root.data);
Assert.AreEqual(2, root.right.data);
Assert.AreEqual(3, root.right.right.data);
Assert.AreEqual(4, root.right.right.right.data);
Assert.AreEqual(5, root.right.right.right.right.data);
Assert.AreEqual(6, root.right.right.right.right.right.data);
}
public void Flatten(TreeNode root)
{
if (root == null || (root.left == null && root.right == null))
{
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
var head = root;
stack.Push(root);
while (stack.Count > 0)
{
var curr = stack.Pop();
if (curr != root) // in the first iteration, we don't want to move the head to the next item
{
head.right = curr;
head = curr;
}
if (curr.right != null)
{
stack.Push(curr.right);
curr.right = null;
}
if (curr.left != null)
{
stack.Push(curr.left);
curr.left = null;
}
}
}
}
}