I'm trying to solve this problem in C# and I keep getting a null reference exception runtime issue. Not sure exactly what is causing this.. Can anyone help? Here's my code:
/*
// Definition for a Node.
public class Node {
public int val;
public IList<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, IList<Node> _children) {
val = _val;
children = _children;
}
}
*/
public class WrappableInt {
private int val;
public WrappableInt(int x) {
val = x;
}
public int getValue() {
return val;
}
public void increment() {
val++;
}
}
public class Codec {
// Encodes a tree to a single string.
public string serialize(Node root) {
StringBuilder sb = new StringBuilder();
serializeHelper(root, sb);
return sb.ToString();
}
public void serializeHelper(Node node, StringBuilder sb) {
if(node == null) {
return;
}
sb.Append(node.val);
sb.Append(node.children.Count);
foreach(Node child in node.children) {
serializeHelper(child, sb);
}
}
// Decodes your encoded data to tree.
public Node deserialize(string data) {
Console.WriteLine(data);
if(String.IsNullOrEmpty(data)) {
return null;
}
return deserializeHelper(data, new WrappableInt(0));
}
public Node deserializeHelper(string data, WrappableInt index) {
if(index.getValue() >= data.Length) {
return null;
}
Node node = new Node(data[index.getValue()], new List<Node>());
index.increment();
var num = data[index.getValue()];
for(int i = 0; i < num; ++i) {
index.increment();
node.children.Add(deserializeHelper(data, index));
}
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));And the error:
System.NullReferenceException: Object reference not set to an instance of an object.
Line 72: Serialize.serialize (Node root) in __Driver__.cs
Line 107: __Driver__.Main (System.String[] args) in __Driver__.cs
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object.
Line 72: Serialize.serialize (Node root) in __Driver__.cs
Line 107: __Driver__.Main (System.String[] args) in __Driver__.cs