Mark Mark - 20 days ago 5
C# Question

why does c# list add reference to the variable?

Ok so when I run this function I expect to get a list of linkendlist referencing nodes at each level of a binary tree. However this function returns empty linkendlists for all levels. Could someone tell me why? I have added solution in java as well.

public static void Main()
{
BinaryTree t = new BinaryTree(0);

BinaryTree l1 = new BinaryTree(1);
BinaryTree l2 = new BinaryTree(2);
BinaryTree l3 = new BinaryTree(3);
BinaryTree l4 = new BinaryTree(4);
BinaryTree l5 = new BinaryTree(5);
BinaryTree l6 = new BinaryTree(6);

t.left = l1;
t.right = l4;

l1.left = l2;
l1.right = l3;

l4.left = l5;
l4.right = l6;

List<LinkedList<BinaryTree>> lod = ListOfDepth(t);

// this will print empty list
foreach (var item in lod)
{
foreach (var lst in item)
{
Console.Write(lst.data);

}
Console.WriteLine();
}


}
public class BinaryTree
{
public BinaryTree(int d) { data = d; }
public BinaryTree() { }
public int id;
public int data;
public BinaryTree left = null;
public BinaryTree right = null;
}

public static List<LinkedList<BinaryTree>> ListOfDepth(BinaryTree t)
{
List<LinkedList<BinaryTree>> lst = new List<LinkedList<BinaryTree>>();
// add current level to lst
LinkedList<BinaryTree> curLevel = new LinkedList<BinaryTree>();
curLevel.AddLast(t);
lst.Add(curLevel);

LinkedList<BinaryTree> newLevel = new LinkedList<BinaryTree>();
while (curLevel.Count > 0)
{
BinaryTree curNode = curLevel.First.Value;
curLevel.RemoveFirst();

if (curNode.left != null)
{
newLevel.AddLast(curNode.left);
}
if (curNode.right != null)
{
newLevel.AddLast(curNode.right);
}

if (curLevel.Count == 0)
{
curLevel = newLevel;
if (newLevel.Count > 0)
{
lst.Add(newLevel);
}
newLevel = new LinkedList<BinaryTree>();

}

}

return lst;
}


Java Version.

ArrayList<LinkedList<BinaryTree>> listofDepth(BinaryTree root) {
ArrayList<LinkedList<BinaryTree>> result = new ArrayList<LinkedList<BinaryTree>>();
LinkedList<BinaryTree> current = new LinkedList<BinaryTree>();
if (root != null) {
current.add(root);
}

while (current.size() > 0) {
result.add(current);
LinkedList<BinaryTree> parents = current;
current = new LinkedList<BinaryTree>();

for (BinaryTree parent : parents) {
if (parent.left != null) {
current.add(parent.left);
}
if (parent.right != null) {
current.add(parent.right);
}
}

}
return result;
}

Answer

The problem is obvious. In the Java version of your code, you use a variable current from the outside of your method, where you add an item (root) to.

In the C# version, you don't have that variable and hence it doesn't get added to the current. Instead, you create a new variable inside your method to add it to. Those are two totally different code blocks.

Comments