Trees

Comprehensive study notes, diagrams, and exam preparation for Trees.

Trees in Java Collections Framework

Definition

A Tree is a non-linear, hierarchical data structure that organizes data elements in a parent-child relationship. Unlike arrays or linked lists where data is stored sequentially, a tree consists of a root node with branches leading to child nodes, resembling an inverted biological tree. In Java, trees are fundamental for implementing sorted collections and efficient search algorithms.


Main Content

1. Hierarchy and Nodes

  • A Tree starts with a single 'Root' node at the top.
  • Each node can have zero or more children; a node without children is called a 'Leaf' node.
      (Root)
       /  \
     (A)  (B)
     / \    \
   (C) (D)  (E)

2. Binary Search Tree (BST) Properties

  • Every node in a BST has at most two children, referred to as the 'Left' child and 'Right' child.
  • For any given node, all elements in the left subtree are smaller, and all elements in the right subtree are larger.

3. Java Collection Implementations

  • The TreeSet class implements the Set interface, ensuring all elements are stored in sorted order.
  • The TreeMap class implements the Map interface, storing key-value pairs sorted by the keys.

Working / Process

1. Node Insertion

  • Start at the root node.
  • If the tree is empty, the inserted value becomes the root.
  • Compare the new value with the current node: if smaller, move left; if larger, move right, repeating until an empty spot is found.

2. Search Operation

  • Start at the root and compare the target value with the node's value.
  • If the target matches, the search is successful.
  • If the target is smaller, navigate to the left child; if larger, navigate to the right child until found or a leaf is reached.

3. Traversal Mechanism

  • In-order traversal visits nodes in the order: Left Subtree -> Root -> Right Subtree.
  • This process effectively sorts the elements of a tree in ascending order when processed through Java's collection framework methods.

Advantages / Applications

  • Search, insertion, and deletion operations are significantly faster than linear structures, typically occurring in logarithmic time O(log n).
  • Trees are excellent for maintaining hierarchical data, such as file systems or XML/HTML document structures.
  • They provide dynamic memory allocation, automatically growing and shrinking as elements are added or removed from TreeSet or TreeMap.

Summary

A tree is a hierarchical data structure in Java that maintains elements in a sorted order using nodes connected by parent-child relationships. It is primarily utilized through the TreeSet and TreeMap classes to ensure efficient searching and organized data storage. Important terms to remember include Root (the top node), Leaf (nodes with no children), Binary Search Tree (a tree with specific sorting rules), and Traversal (the method of visiting every node).