deserializeTree<T> function

BinaryTreeNode<T>? deserializeTree<T>(
  1. String data
)

Deserializes a string back to a binary tree

Reconstructs the tree from the serialized string format.

Implementation

BinaryTreeNode<T>? deserializeTree<T>(String data) {
  if (data.isEmpty) return null;

  final List<String> values = data.split(",");
  if (values.isEmpty || values[0] == "null") return null;

  // Helper function to parse value based on type
  T parseValue(String value) {
    if (T == int) {
      return int.parse(value) as T;
    } else if (T == double) {
      return double.parse(value) as T;
    } else {
      // For strings, we need to handle the case where the value might contain commas
      // This is a simplified approach - in practice, you might want to use a more robust serialization format
      return value as T;
    }
  }

  final BinaryTreeNode<T> root = BinaryTreeNode<T>(parseValue(values[0]));
  final List<BinaryTreeNode<T>?> queue = [root];
  int index = 1;

  while (queue.isNotEmpty && index < values.length) {
    final BinaryTreeNode<T>? node = queue.removeAt(0);

    if (node != null) {
      // Left child
      if (index < values.length && values[index] != "null") {
        node.left = BinaryTreeNode<T>(parseValue(values[index]));
        queue.add(node.left);
      }
      index++;

      // Right child
      if (index < values.length && values[index] != "null") {
        node.right = BinaryTreeNode<T>(parseValue(values[index]));
        queue.add(node.right);
      }
      index++;
    }
  }

  return root;
}