In: Computer Science
in JAVA: implement a class called tree (from scratch) please be simple so i can understand thanks!
tree(root)
node(value, leftchild,rightchild)
method: insert(value)
Program :
class Tree{
/* Class containing left and right child of current node and key value*/
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
// Root of tree
Node root;
// Constructor
Tree() {
root = null;
}
// This method mainly calls insertRec()
void insert(int key) {
root = insertRec(root, key);
}
/* A recursive function to insert a new key in BST */
Node insertRec(Node root, int key) {
/* If the tree is empty, return a new node */
if (root == null) {
root = new Node(key);
return root;
}
/* Otherwise, recur down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the (unchanged) node pointer */
return root;
}
// This method mainly calls InorderRec()
void print() {
traversal(root);
}
// A utility function to do inorder traversal of tree
void traversal(Node root) {
if (root != null) {
traversal(root.left);
System.out.print(root.key +" ");
traversal(root.right);
}
}
//Main method
public static void main(String[] args) {
Tree tree = new Tree();
tree.insert(55);
tree.insert(67);
tree.insert(89);
tree.insert(90);
tree.insert(23);
tree.insert(56);
tree.insert(80);
System.out.print("Output is :");
tree.print();
}
}
Output :
Thank You Have a great Day !!! Please do like.