0% found this document useful (0 votes)
10 views

BST Operations in Java PDF

This document provides code examples for implementing common binary search tree operations in Java, including creating nodes, inserting nodes, searching, traversing, and deleting nodes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

BST Operations in Java PDF

This document provides code examples for implementing common binary search tree operations in Java, including creating nodes, inserting nodes, searching, traversing, and deleting nodes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Name: Basir. F/Name: Wali Khan.

Dep:IS

____________________________

Sure, here are some examples of how to implement BST operations in Java:

1. Creating a new BST node:

```

class Node {

int key;

Node left, right;

public Node(int item) {

key = item;

left = right = null;

```

2. Inserting a new node into the BST:

```

public Node insert(Node root, int key) {

if (root == null) {

root = new Node(key);

return root;

if (key < root.key) {

root.left = insert(root.left, key);


} else if (key > root.key) {

root.right = insert(root.right, key);

return root;

```

3. Finding a node in the BST:

```

public Node search(Node root, int key) {

if (root == null || root.key == key) {

return root;

if (root.key < key) {

return search(root.right, key);

return search(root.left, key);

```

4. Traversing the BST in-order:

```

public void inorder(Node root) {

if (root != null) {
inorder(root.left);

System.out.print(root.key + " ");

inorder(root.right);

```

5. Deleting a node from the BST:

```

public Node delete(Node root, int key) {

if (root == null) {

return root;

if (key < root.key) {

root.left = delete(root.left, key);

} else if (key > root.key) {

root.right = delete(root.right, key);

} else {

if (root.left == null) {

return root.right;

} else if (root.right == null) {

return root.left;

root.key = minValue(root.right);

root.right = delete(root.right, root.key);


}

return root;

public int minValue(Node root) {

int minValue = root.key;

while (root.left != null) {

minValue = root.left.key;

root = root.left;

return minValue;

```

These are just examples and there are many other methods of implementing BST operations in Java.

You might also like