Created
February 14, 2019 10:52
-
-
Save ochim/dbc95ab2a55ed4b78304bd9ea09e3b5d to your computer and use it in GitHub Desktop.
二分探索木
This file contains hidden or 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
| // 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