Last active
December 13, 2015 21:08
-
-
Save apremalal/4975299 to your computer and use it in GitHub Desktop.
This is an implementation of the binary search tree.
Reference - Introduction to Algorithms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BinarySearchTree { | |
void in_order_tree_walk(Node x) { | |
in_order_tree_walk(x.left); | |
System.out.println(x.key); | |
in_order_tree_walk(x.right); | |
} | |
void insert(Node T, Node x) { | |
Node y = T; | |
while (y != null) { | |
if (y.key < x.key) { | |
if (y.right == null) | |
y.right = x; | |
else | |
y = y.right; | |
} else { | |
if (y.left == null) | |
y.left = x; | |
else | |
y = y.left; | |
} | |
} | |
} | |
Node minimum(Node x) { | |
while (x.left != null) { | |
x = x.left; | |
} | |
return x; | |
} | |
Node maximum(Node x) { | |
while (x.right != null) { | |
x = x.right; | |
} | |
return x; | |
} | |
Node treeSearch(Node x, int key) { | |
if (x == null || x.key == key) { | |
return x; | |
} | |
if (x.key < key) { | |
return treeSearch(x.left, key); | |
} else { | |
return treeSearch(x.right, key); | |
} | |
} | |
Node itereativeTreeSearch(Node x, int key) { | |
while (x != null && x.key != key) { | |
if (x.key < key) | |
x = x.right; | |
else | |
x = x.left; | |
} | |
return x; | |
} | |
} | |
class Node { | |
Node left; | |
Node right; | |
int key; | |
Node(int key) { | |
this.key = key; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment