-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertmainmethod.java
More file actions
73 lines (59 loc) · 2.52 KB
/
Insertmainmethod.java
File metadata and controls
73 lines (59 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
*/
package com.mycompany.insertmainmethod;
/**
*
* @author HP
*/
public class Insertmainmethod {
public static void main(String[] args) {
Binarytreeinsert root = null; // Initialize an empty tree
// Insert nodes into the tree
root = insert(root, 10); // Insert node with data 10
root = insert(root, 5); // Insert node with data 5
root = insert(root, 15); // Insert node with data 15
// Print root and its left and right children to verify
System.out.println("Root Node: " + root.data);
if (root.leftChild != null) {
System.out.println("Root's Left Child: " + root.leftChild.data);
}
if (root.rightChild != null) {
System.out.println("Root's Right Child: " + root.rightChild.data);
}
}
// Insert method that takes a root and data and returns the new root
public static Binarytreeinsert insert(Binarytreeinsert root, int data) {
// Create a new node with the specified data
Binarytreeinsert tempNode = new Binarytreeinsert(data);
// If the tree is empty, set the new node as the root
if (root == null) {
return tempNode;
} else {
Binarytreeinsert current = root; // Start traversal from the root
Binarytreeinsert parent = null; // Keep track of the parent node
// Traverse the tree to find the correct insertion point
while (true) {
parent = current;
// If data is less than the current node's data, go to the left child
if (data < current.data) {
current = current.leftChild;
// If the left child is null, insert the new node here
if (current == null) {
parent.leftChild = tempNode;
return root; // Return the original root
}
}
// If data is greater than or equal to the current node's data, go to the right child
else {
current = current.rightChild;
// If the right child is null, insert the new node here
if (current == null) {
parent.rightChild = tempNode;
return root; // Return the original root
}
}
}
}
}
}