0% found this document useful (0 votes)
20 views2 pages

lab5q3

Uploaded by

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

lab5q3

Uploaded by

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

class TreeNode {

int key;
TreeNode left, right;

public TreeNode(int item) {


key = item;
left = right = null;
}
}

public class BinarySearchTree {


private TreeNode root;

public BinarySearchTree() {
root = null;
}

// In-order traversal
public void inOrderTraversal() {
inOrderTraversal(root);
}

private void inOrderTraversal(TreeNode root) {


if (root != null) {
inOrderTraversal(root.left);
System.out.print(root.key + " ");
inOrderTraversal(root.right);
}
}

// Insert a key into the BST


public void insert(int key) {
root = insert(root, key);
}

private TreeNode insert(TreeNode root, int key) {


if (root == null) {
return new TreeNode(key);
}

if (key < root.key) {


root.left = insert(root.left, key);
} else if (key > root.key) {
root.right = insert(root.right, key);
}

return root;
}

public static void main(String[] args) {


BinarySearchTree bst = new BinarySearchTree();

// Insert some keys


bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);

// In-order traversal to display keys in increasing order


System.out.println("In-Order Traversal:");
bst.inOrderTraversal(); // Should print 20 30 40 50 60 70 80
}
}

You might also like