Trees
This content is for DSA. Switch to the latest version for up-to-date documentation.

A tree is a hierarchical data structure consisting of nodes connected by edges. It resembles an upside-down tree with a root at the top and branches extending downward. Each node can have multiple children, but only one parent (except the root node which has no parent).
Properties
Section titled “Properties”- Hierarchical structure with parent-child relationships: Nodes are organized in levels with clear parent-child connections.
- One root node (no parent): The top-most node that serves as the starting point of the tree.
- Each node can have multiple children: Nodes can branch out to any number of child nodes.
- N nodes have N-1 edges: A tree with N nodes always has exactly N-1 connecting edges.
Use Cases
Section titled “Use Cases”- File systems: Representing folder and file hierarchies in operating systems.
- Binary Tree: Each node has at most 2 children
Operations
Section titled “Operations”- Search: Find a specific value in the tree.
- Insertion: Add a new node to the tree.
- Deletion: Remove a node from the tree.
- Traversal: Visit all nodes in a specific order (Inorder, Preorder, Postorder).
Traversal Methods
Section titled “Traversal Methods”- Inorder: Left → Root → Right
- Preorder: Root → Left → Right
- Postorder: Left → Right → Root
- Level order: Breadth-first traversal
Advantages
Section titled “Advantages”- Efficient searching and sorting: Balanced trees provide logarithmic time complexity for common operations.
- Hierarchical data representation: Natural way to represent data with parent-child relationships.
- Dynamic size: Can grow and shrink as needed during runtime.
- Various traversal methods: Multiple ways to visit and process nodes.
Disadvantages
Section titled “Disadvantages”- No constant time operations: Most operations require traversing the tree structure.
- Complex implementation: More complex to implement compared to linear data structures.
- Recursive nature: Many tree algorithms are recursive, which can cause stack overflow for very deep trees.
Example
Section titled “Example”// Simple binary tree node classclass TreeNode { int data; TreeNode left; TreeNode right;
TreeNode(int value) { this.data = value; this.left = null; this.right = null; }}
// Creating a binary treeTreeNode root = new TreeNode(1); // Root noderoot.left = new TreeNode(2); // Left child of rootroot.right = new TreeNode(3); // Right child of rootroot.left.left = new TreeNode(4); // Left child of node 2root.left.right = new TreeNode(5); // Right child of node 2
// Tree structure:// 1// / \// 2 3// / \// 4 5
// Inorder traversal (Left -> Root -> Right)public void inorderTraversal(TreeNode node) { if (node != null) { inorderTraversal(node.left); // Visit left subtree System.out.print(node.data + " "); // Visit root inorderTraversal(node.right); // Visit right subtree }}
// Usage: inorderTraversal(root); // Output: 4 2 5 1 3