package tree;
public class BinarySearchTree<T extends Comparable<? super T>>{
private BinaryNode<T> root;
private static class BinaryNode<T>{
T element; //data
BinaryNode<T>left; //left child
BinaryNode<T>right; //right child
public BinaryNode(T element) {
constructor stub
this(element, null, null);
}
public BinaryNode(T theElement,BinaryNode<T> theLeft,BinaryNode<T>theRight) {
constructor stub
left=theLeft;
element=theElement;
right=theRight;
}
}
public BinarySearchTree(){
root=null;
}
public void makeEmpty(){
root=null;
}
public boolean isEmpty(){
return root==null;
}
public boolean contains(T value){
return contains(value,root);
}
public T findMin(){
return findMin(root).element;
}
public T findMax(){
return findMax(root).element;
}
public void insert(T value){
root=insert(value, root);
}
public void remove(T value){
root=remove(value, root);
}
//反转二叉树
public void invertBinaryTree(BinaryNode<T> node){
if (node==null) {
return;
}
BinaryNode<T> temp=node.left;
node.left=node.right;
node.right=temp;
invertBinaryTree(node.left);
invertBinaryTree(node.right);
}
public void printTree(){
if (isEmpty()) {
System.out.println("Empty Tree");
}
else {
printTree(root);
}
}
//中序遍历
private void printTree(BinaryNode<T> node){
if (node!=null) {
printTree(node.left);
System.out.println(node.element);
printTree(node.right);
}
}
private int height(BinaryNode<T> node){
if (node==null) {
return -1;
}
else {
return 1+Math.max(height(node.left), height(node.right));
}
}
private boolean contains(T value,BinaryNode<T> node){
if (node==null) {
return false;
}
int compareResult=value.compareTo(node.element);
if (compareResult<0) {
return contains(value, node.left);
}
else if (compareResult>0) {
return contains(value, node.right);
}
else {
return true;
}
}
private BinaryNode<T> findMin(BinaryNode<T> node){
if (node==null) {
return null;
}
else if (node.left==null) {
return node;
}
return findMin(node.left);
}
private BinaryNode<T> findMax(BinaryNode<T> node){
if (node==null) {
return null;
}
else if (node.right==null) {
return node;
}
return findMax(node.right);
}
private BinaryNode<T> insert(T value,BinaryNode<T> node){
if (node==null) {
return new BinaryNode<T>(value, null, null);
}
int compareResult=value.compareTo(node.element);
if (compareResult<0) {
node.left=insert(value, node.left);
}
else if (compareResult>0) {
node.right=insert(value, node.right);
}
else {
}
return node;
}
private BinaryNode<T> remove(T value,BinaryNode<T>node){
if (node==null) {
return node;
}
int compareResult=value.compareTo(node.element);
if (compareResult<0) {
node.left=remove(value, node.left);
}
else if (compareResult>0) {
node.right=remove(value, node.right);
}
else if (node.left!=null && node.right!=null) { //有两个孩子
node.element=findMin(node.right).element;
node.right=remove(node.element, node.right);
}
else {
node=(node!=null)?node.left:node.right;
}
return node;
}
}
数据结构之二叉查找树
最新推荐文章于 2022-08-18 12:10:58 发布