https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/
Got unknown runtime error with following code
Error:
java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "<local4>.children" is null
at line 134, Serializer.serializeRoot
at line 188, __Driver__.mainCode:
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Codec {
// Encodes an n-ary tree to a binary tree.
public TreeNode encode(Node root) {
if(root == null) return null;
TreeNode r = new TreeNode(root.val);
if(root.children != null
&& !root.children.isEmpty()){
TreeNode child = encode(root.children.get(0));
r.left = child;
for(int i=1;i < root.children.size();i++){
child.right = encode(root.children.get(i));
child = child.right;
}
}
return r;
}
// Decodes your binary tree to an n-ary tree.
public Node decode(TreeNode root) {
if(root == null) return null;
Node ans = new Node(root.val);
if(root.left != null){
ans.children = new LinkedList<>();
TreeNode child = root.left;
while(child != null) {
ans.children.add(decode(child));
child = child.right;
}
}
return ans;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(root));