0% found this document useful (0 votes)
11 views3 pages

Bfs PGM

binary first search

Uploaded by

sas28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Bfs PGM

binary first search

Uploaded by

sas28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

import java.util.

Scanner;

class Node {

int data;

Node left, right;

Node(int data) {

this.data = data;

left = right = null;

class BinaryTree {

Node root;

void insert(int data) {

root = insertRec(root, data);

Node insertRec(Node root, int data) {

if (root == null) {

return new Node(data);

if (data < root.data) {

root.left = insertRec(root.left, data);

} else {

root.right = insertRec(root.right, data);

return root;

void inorder(Node node) {

if (node != null) {

inorder(node.left);

System.out.print(node.data + " ");

inorder(node.right);
}

void preorder(Node node) {

if (node != null) {

System.out.print(node.data + " ");

preorder(node.left);

preorder(node.right);

void postorder(Node node) {

if (node != null) {

postorder(node.left);

postorder(node.right);

System.out.print(node.data + " ");

void traverse() {

System.out.println("Inorder traversal:");

inorder(root);

System.out.println("\nPreorder traversal:");

preorder(root);

System.out.println("\nPostorder traversal:");

postorder(root);

System.out.println();

public class BinaryTreeTraversal {

public static void main(String[] args) {

BinaryTree tree = new BinaryTree();

Scanner scanner = new Scanner(System.in);


System.out.println("Enter number of nodes:");

int n = scanner.nextInt();

System.out.println("Enter node values:");

for (int i = 0; i < n; i++) {

tree.insert(scanner.nextInt());

tree.traverse();

scanner.close();

You might also like