public class BinarySearchTree { class Node { int key; Node left, right; public Node(int item) { key = item; left = right

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

public class BinarySearchTree { class Node { int key; Node left, right; public Node(int item) { key = item; left = right

Post by answerhappygod »

public class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
// Root of BST
Node root;
// Constructor
BinarySearchTree() { root = null; }
BinarySearchTree(int value) { root = new Node(value); }
// 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);
else if (key > root.key)
root.left.left = insertRec(root.left.left, key);
/* return the (unchanged) node pointer */
return root;
}
// This method mainly calls InorderRec()
void preorder() { preorderRec(root); } // Inorder recursive
function
// A utility function to
// do inorder traversal of BST
void preorderRec(Node root)
{
if (root != null) {
preorderRec(root.left);
System.out.println(root.key);
preorderRec(root.right);
}
}
// Driver Code
public static void main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
tree.insert(20);
tree.insert(30);
tree.insert(50);
tree.insert(40);
tree.insert(100);
tree.insert(60);
tree.insert(80);
tree.insert(70); // print preorder traversal of the BST
tree.preorder();
}
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply