Skip to content

Instantly share code, notes, and snippets.

@sheep0x
Created July 31, 2015 08:48
Show Gist options
  • Save sheep0x/0f4197a5d6b803129bf3 to your computer and use it in GitHub Desktop.
Save sheep0x/0f4197a5d6b803129bf3 to your computer and use it in GitHub Desktop.
CS 61B/61BL style BST in Java
/*
* Copyright 2015 Chen Ruichao <linuxer.sheep.0x@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO change to CC0
/**
* CS 61B/61BL style BST. Of course there are other ways to do it.
*/
public class PlainBST {
private static class Node {
int item;
Node left;
Node right;
// ...
}
Node root;
public PlainBST() {
// ...
}
public void insert(int v) {
root = insert(root, v);
}
public void remove(int v) {
root = remove(root, v);
}
private static Node insert(Node p, int v) {
if (p == null) {
return new Node(v);
}
if (v < p.item) p.left = insert(p.left , v);
if (v > p.item) p.right = insert(p.right, v);
// if v == p.item, do nothing
return p;
}
// 30 lines! I guess this is not the shortest way to implement, but
// anyways... As long as you guys can understand.
private static Node remove(Node p, int v) {
if (p == null) {
return null;
}
if (v < p.item) {
p.left = remove(p.left, v); // p.left may be null or not null, but in both cases this will work
return p;
}
if (v > p.item) {
p.right = remove(p.right, v); // p.right may be null or not null, but in both cases this will work
return p;
}
// otherwise, v == p.item
if (p.right == null) {
return p.left; // p.left might be null or not null, but in both cases this will work
}
// otherwise, p.right != null
// find inorder successor
Node succ = p.right;
while (succ.left != null) {
succ = succ.left;
}
p.item = succ.item;
p.right = remove(p.right, succ.item);
return p;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment