preorderTraversal<T> function

List<T> preorderTraversal<T>(
  1. BinaryTreeNode<T>? root
)

Preorder Traversal: Root -> Left -> Right

Useful for copying trees or serialization.

Example:

final root = BinaryTreeNode<int>(10);
root.left = BinaryTreeNode<int>(5);
root.right = BinaryTreeNode<int>(15);
final result = preorderTraversal(root);
// result: [10, 5, 15]

Implementation

List<T> preorderTraversal<T>(BinaryTreeNode<T>? root) {
  final List<T> result = [];

  void preorder(BinaryTreeNode<T>? node) {
    if (node == null) return;
    result.add(node.value);
    preorder(node.left);
    preorder(node.right);
  }

  preorder(root);
  return result;
}