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

Java Binary Search Tree Implementation

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)
42 views2 pages

Java Binary Search Tree Implementation

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

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([Link]);
[Link]([Link] + " ");
inOrderTraversal([Link]);
}
}

// 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 < [Link]) {


[Link] = insert([Link], key);
} else if (key > [Link]) {
[Link] = insert([Link], key);
}

return root;
}

public static void main(String[] args) {


BinarySearchTree bst = new BinarySearchTree();

// Insert some keys


[Link](50);
[Link](30);
[Link](20);
[Link](40);
[Link](70);
[Link](60);
[Link](80);

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


[Link]("In-Order Traversal:");
[Link](); // Should print 20 30 40 50 60 70 80
}
}

You might also like