Mark As Completed Discussion

Binary Trees

In the world of data structures, a binary tree is a type of tree where each node has at most two children, referred to as the left child and the right child. The binary tree is named so because each node can have at most two children, making it a binary relation.

Binary trees are widely used in various areas of computer science, such as search algorithms, sort algorithms, and decision trees.

To understand the concept of binary trees, let's take a look at a simple example:

TEXT/X-JAVA
1class Node {
2    int data;
3    Node left;
4    Node right;
5
6    Node(int data) {
7        this.data = data;
8        left = null;
9        right = null;
10    }
11}
12
13public class BinaryTree {
14    Node root;
15
16    public BinaryTree() {
17        root = null;
18    }
19
20    public static void main(String[] args) {
21        BinaryTree tree = new BinaryTree();
22
23        // Create the root node
24        tree.root = new Node(1);
25
26        // Create the left and right child nodes
27        tree.root.left = new Node(2);
28        tree.root.right = new Node(3);
29
30        // Print the binary tree
31        tree.printBinaryTree();
32    }
33
34    public void printBinaryTree() {
35        printBinaryTree(root, 0);
36    }
37
38    private void printBinaryTree(Node node, int level) {
39        if (node == null) {
40            return;
41        }
42
43        // Print right child nodes recursively
44        printBinaryTree(node.right, level + 1);
45
46        // Indentation for current node based on level
47        for (int i = 0; i < level; i++) {
48            System.out.print("\t");
49        }
50
51        // Print current node
52        System.out.println(node.data);
53
54        // Print left child nodes recursively
55        printBinaryTree(node.left, level + 1);
56    }
57}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment