Mark As Completed Discussion

Trees

In computer science, a tree is a widely-used abstract data type that resembles a hierarchical structure. It consists of nodes connected by edges. The topmost node in the tree is called the root, while the nodes at the bottom are called leaves.

Trees provide an organized way of storing and accessing data. They are especially useful when we need to represent hierarchical relationships or perform operations such as searching, insertion, and deletion efficiently.

There are various types of trees, including binary trees, AVL trees, B-trees, and heaps. Each type has its own characteristics and operations associated with it.

Binary Trees

A binary tree is a tree in which each node can have at most two children, referred to as the left child and the right child. The left child is smaller than the parent node, while the right child is greater. Binary trees are commonly used and implemented in various algorithms and data structures.

Here's an example of creating a binary tree and accessing its nodes in Java:

TEXT/X-JAVA
1class Main {
2  public static void main(String[] args) {
3
4    // Creating a binary tree
5    TreeNode rootNode = new TreeNode(1);
6    TreeNode leftChild = new TreeNode(2);
7    TreeNode rightChild = new TreeNode(3);
8    rootNode.left = leftChild;
9    rootNode.right = rightChild;
10
11    // Accessing tree nodes
12    System.out.println("Root Node: " + rootNode.val);
13    System.out.println("Left Child: " + rootNode.left.val);
14    System.out.println("Right Child: " + rootNode.right.val);
15  }
16}
17
18class TreeNode {
19  int val;
20  TreeNode left;
21  TreeNode right;
22
23  public TreeNode(int val) {
24    this.val = val;
25  }
26}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment