Write a Java Program to Implement Binary Tree Data Structure

Java Program to Implement Binary Tree Data Structure

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Implement Binary Tree Data Structure
Java Program to Implement Binary Tree Data Structure

Write a Java Program to Implement Binary Tree Data Structure

PROGRAM: Java Program to Implement Binary Tree Data Structure

/*Java Program to Implement Binary Tree Data Structure*/

// class to create nodes
class Node {
int key;
Node left, right;

public Node(int item) {
key = item;
left = right = null;
}
}

class BinaryTree {
Node root;

// Traverse tree
public void traverseTree(Node node) {
if (node != null) {
traverseTree(node.left);
System.out.print(” ” + node.key);
traverseTree(node.right);
}
}

public static void main(String[] args) {

// create an object of BinaryTree
BinaryTree tree = new BinaryTree();

// create nodes of the tree
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);

System.out.print(“\nBinary Tree: “);
tree.traverseTree(tree.root);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *