using System; class Node { public int Value; public Node Left, Right; public Node(int val) { Value = val; Left = Right = null; } } class ListNode { public int Value; public ListNode Next; public ListNode(int val) { Value = val; Next = null; } } class Program { static void InOrder(Node root) { if (root == null) return; InOrder(root.Left); Console.Write(root.Value + " "); InOrder(root.Right); } static void TraverseList(ListNode head) { var current = head; while (current != null) { Console.Write(current.Value + " "); current = current.Next; } } static void Main() { // Binary tree: // 2 // / \ // 1 3 Node root = new Node(2); root.Left = new Node(1); root.Right = new Node(3); // Linked list: 1 -> 2 -> 3 ListNode head = new ListNode(1); head.Next = new ListNode(2); head.Next.Next = new ListNode(3); InOrder(root); Console.WriteLine(); TraverseList(head); } }
The in-order traversal of the binary tree visits nodes in ascending order: left child, root, right child, so it prints "1 2 3".
The linked list is traversed from head to tail, printing "1 2 3" as inserted.
Trees allow each node to have multiple children, which fits hierarchical data like folders and files. Arrays and linked lists are linear and do not naturally represent branching.
class Node { public int Value; public Node Left, Right; public Node(int val) { Value = val; Left = Right = null; } } bool Search(Node root, int target) { if (root == null) return false; if (root.Value == target) return true; if (target < root.Value) return Search(root.Left, target); else return Search(root.Right, target); }
The recursive calls to Search do not return their results, so the function always returns false unless the root matches the target.
using System; class Node { public int Value; public Node Left, Right; public Node(int val) { Value = val; Left = Right = null; } } class Program { static int Height(Node root) { if (root == null) return 0; int leftHeight = Height(root.Left); int rightHeight = Height(root.Right); return Math.Max(leftHeight, rightHeight) + 1; } static void Main() { Node root = new Node(10); root.Left = new Node(5); root.Right = new Node(15); root.Left.Left = new Node(3); root.Left.Left.Left = new Node(1); Console.WriteLine(Height(root)); } }
The longest path is from root (10) to left-left-left (1), which has 4 nodes, so height is 4.
Arrays and linked lists are linear, so representing multiple children per node requires extra complexity. Trees naturally model branching with nodes having multiple children.
