Binary Tree

What are Binary Tree?
In the Article, we will Discuss about the Binary Tree of java.
A binary tree in Java is a data structure consisting of nodes, each of which has at most two child nodes. The tree is called “binary” because each node can have at most two children.
Java Binary Tree:
A binary tree is a type of tree data structure in which each node has at most two children, referred to as the left child and the right child.
Here are some important properties of binary trees:
- Each node in a binary tree has at most two children.
- The topmost node of the tree is called the root node.
- Nodes with no children are called leaf nodes or terminal nodes.
- The height of a binary tree is the length of the longest path from the root node to a leaf node.
- The depth of a node in a binary tree is the length of the path from the root node to that node.

A binary tree can be defined recursively as follows: a binary tree is either empty (null) or consists of a node, called the root, and two subtrees, called the left subtree and the right subtree. Each of the subtrees is also a binary tree.
In Java, binary trees are usually implemented using a Node class. Each node contains a data element and references to its left and right child nodes, which can be null if there are no children.
Types of Binary Tree:





Java Program to Implement Binary Tree:
class Node { int data; Node left; Node right; public Node(int data){ this.data = data; this.left = null; this.right = null; } } class BinaryTree { Node root; public BinaryTree(){ this.root = null; } public void insert(int data){ root = insertRec(root, data); } private Node insertRec(Node root, int data){ if (root == null) { root = new Node(data); return root; } if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); return root; } }
Explanation:
In the above program, the Node class contains an integer data element and references to the left and right child nodes. The BinaryTree class contains a reference to the root node and methods for inserting nodes into the tree recursively.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment