Java program to construct a Binary Search Tree and perform insert and In-order traversal

preview_player
Показать описание
#BackCoding

we need to create a binary search tree, insert a node from the tree, and display the nodes of the tree by traversing the tree using in-order traversal.

In Binary Search Tree, all nodes which are present to the left of root will be less than root node and nodes which are present to the right will be greater than the root node.

insert() will insert the new value into a binary search tree:

It checks whether root is null, which means tree is empty. New node will become root node of tree.
If tree is not empty, it will compare value of new node with root node. If value of new node is greater than root, new node will be inserted to right subtree. Else, it will be inserted in left subtree.

#programming
#shorts
#dcoder
#java
Рекомендации по теме
Комментарии
Автор

class BST{
private static class Node{

int data;
Node left;
Node right;

public Node(int data){
this.data=data;
}

}
public static Node insert (Node root, int val){
if(root==null){
root=new Node(val);
return root;
}
if(root.data>val){
root.left=insert (root.left, val);
}
else{
root.right=insert (root.right, val);
}
return root;
}
public static void inorder(Node root){
if(root==null){
return;
}
inorder(root.left);
");
inorder(root.right);
}


public static void main(String args[]){

int value[]={3, 4, 6, 2, 7, 9, 5, 8};
Node root=null;

for(int i=0;i<value.length;i++){
root=insert(root, value[i]);
}
inorder(root);
}
}

BackCoding
Автор

The music brings back so many memories and thank you for this !

vis.
welcome to shbcf.ru