Skip to content

Instantly share code, notes, and snippets.

@ochim
Created February 14, 2019 10:52
Show Gist options
  • Select an option

  • Save ochim/dbc95ab2a55ed4b78304bd9ea09e3b5d to your computer and use it in GitHub Desktop.

Select an option

Save ochim/dbc95ab2a55ed4b78304bd9ea09e3b5d to your computer and use it in GitHub Desktop.
二分探索木
// How to Implement Binary Search Tree in Java? Example
// https://javarevisited.blogspot.com/2015/10/how-to-implement-binary-search-tree-in-java-example.html#axzz4wnEtnNB3
import java.util.Stack;
public class BST {
private class Node {
private int data;
private Node left, right;
public Node(int value){
data = value;
left = right = null;
}
}
private Node root;
public BST() {
root = null;
}
public Node getRoot() {
return root;
}
public boolean isEmpty() {
return null == root;
}
public int size() {
Node current = root;
int size = 0;
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || current != null){
if (current != null){
stack.push(current);
current = current.left;
} else {
size++;
current = stack.pop();
current = current.right;
}
}
return size;
}
public void clear() {
root = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment