class Node { public int Value; public List<Node> Children = new List<Node>(); public Node(int val) { Value = val; } } var root = new Node(1); root.Children.Add(new Node(2)); root.Children.Add(new Node(3)); root.Children[0].Children.Add(new Node(4)); void Preorder(Node node) { Console.Write(node.Value + " "); foreach(var child in node.Children) { Preorder(child); } } Preorder(root);
Preorder traversal prints the root node first, then recursively visits each child from left to right.
Here, root is 1, children are 2 and 3, and 2 has child 4.
Trees are designed to represent hierarchical data with nodes having multiple children and levels.
Arrays and linked lists are linear and do not naturally represent hierarchy.
class Node { public int Value; public Node Next; public Node(int val) { Value = val; } } var root = new Node(1); root.Next = new Node(2); root.Next.Next = new Node(3); root.Next.Next.Next = root; // creates a cycle Node current = root; int count = 0; while(current != null && count < 10) { Console.Write(current.Value + " "); current = current.Next; count++; }
The linked list has a cycle because root.Next.Next.Next points back to root.
The loop prints nodes until count reaches 10, so it prints repeating sequence 1 2 3 1 2 3 ...
int[] treeLevels = {1, 2, 3, 4, 5, 6, 7}; // Level 0: 1 // Level 1: 2, 3 // Level 2: 4, 5, 6, 7 int level = 2; int startIndex = (int)Math.Pow(2, level) - 1; int endIndex = (int)Math.Pow(2, level + 1) - 2; for(int i = startIndex; i <= endIndex && i < treeLevels.Length; i++) { Console.Write(treeLevels[i] + " "); }
Level 2 nodes start at index 3 and end at index 6 in the array.
These are values 4, 5, 6, 7.
Trees allow nodes to be added or removed anywhere without reorganizing the entire structure.
Arrays require shifting elements, and linked lists do not naturally represent multiple children per node.
