serializeTree<T> function
Serializes a binary tree to a string representation
Uses level-order traversal with "null" for missing nodes. The format is: "value1,value2,null,value3,..."
Implementation
String serializeTree<T>(BinaryTreeNode<T>? root) {
if (root == null) return "";
final List<String> result = [];
final List<BinaryTreeNode<T>?> queue = [root];
while (queue.isNotEmpty) {
final BinaryTreeNode<T>? node = queue.removeAt(0);
if (node == null) {
result.add("null");
} else {
result.add(node.value.toString());
queue.add(node.left);
queue.add(node.right);
}
}
// Remove trailing nulls
while (result.isNotEmpty && result.last == "null") {
result.removeLast();
}
return result.join(",");
}