[go: up one dir, main page]

0% found this document useful (0 votes)
12 views4 pages

Tree Insertion

Uploaded by

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

Tree Insertion

Uploaded by

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

insertion code

import java.util.*;

class Node {

int data;

Node left, right;

public Node(int data) {

this.data = data;

left = right = null;

// put main here if file must be Node.java

public static void main(String[] args) {

BinaryTree t1 = new BinaryTree();

t1.insert(10);

t1.insert(20);

t1.insert(30);

t1.insert(40);

t1.insert(50);

System.out.println("Inorder Traversal:");
t1.inorder(t1.root);

class BinaryTree {

Node root;

public BinaryTree() {

root = null;

public void insert(int data) {

Node nn = new Node(data);

if (root == null) {

root = nn;

return;

Queue<Node> que = new LinkedList<>();

que.add(root);

while (!que.isEmpty()) {

Node temp = que.remove();


if (temp.left == null) {

temp.left = nn;

break;

} else if (temp.right == null) {

temp.right = nn;

break;

} else {

que.add(temp.left);

que.add(temp.right);

public void inorder(Node root) {

if (root == null) {

return;

inorder(root.left);

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

inorder(root.right);

You might also like