public class BinaryTree<T extends Comparable<? super T>> {
private static class BinaryNode<T>{
BinaryNode(T element){
this.element=element;
}
BinaryNode(T element,BinaryNode<T> lt,BinaryNode<T> rt) {
this.element=element;
left=lt;
right=rt;
}
private T element;
private BinaryNode<T> left;
private BinaryNode<T> right;
}
内部静态类 使用场景: 外部类需要使用内部类 而内部类无需外部资源
private BinaryNode<T> root;
public BinaryTree() {
// TODO Auto-generated constructor stub
root=null;
}
public BinaryTree(BinaryNode<T> root){
this.root=root;
}
public void makeEmpty(){
root=null;
}
public boolean isEmpty(){
return root==null;
}
public boolean contains(T x){
return contains(x,root);
}
public T findMin(){
return findMin(root).element;
}
public T findMax(){
return findMax(root).element;
}
public void insert(T element){
root=insert(element,root);
}
public void remove(T element){
root=remove(element,root);
}
public void printTree(){
if(isEmpty())
System.out.println("Empty Tree");
else
printTree(root);
}
private boolean contains(T x,BinaryNode<T> root){
if(root==null)
return false;
int compareResult=x.compareTo(root.element);
if(compareResult<0)
return contains(x, root.left);
else if(compareResult>0)
return contains(x, root.right);
else
return true;
}
public BinaryNode<T> findMin(BinaryNode<T> root){
if(root!=null)
while(root.left!=null)
root=root.left;
return root;
}
public BinaryNode<T> findMax(BinaryNode<T> root){
if(root==null)
return null;
else if(root.right==null)
return root;
return findMax(root.right);
}
public BinaryNode<T> insert(T element,BinaryNode<T> root){
if(root==null){
root=new BinaryNode<T>(element);
return root;
}
BinaryNode<T> parent=null;
BinaryNode<T> current=root;
while(current!=null){
int compareResult=element.compareTo(current.element);
if(compareResult<0){
parent=current;
current=current.left;
}
else if(compareResult>0){
parent=current;
current=current.right;
}
else {
return null;
}
}
if(element.compareTo(parent.element)<0)
parent.left=new BinaryNode<T>(element);
else {
parent.right=new BinaryNode<T>(element);
}
return root;
}
private BinaryNode<T> remove(T element,BinaryNode<T> root){
//树为空
if(root==null){
return root;
}
int compareResult=element.compareTo(root.element);
if(compareResult<0){
root.left=remove(element, root.left);
}
else if(compareResult>0)
root.right=remove(element, root.right);
else if(root.left!=null&&root.right!=null){
root.element=findMin(root.right).element;
root.right=remove(root.element, root.right);
}
else {
root=(root.left!=null)?root.left:root.right;
}
return root;
}
private void printTree(BinaryNode<T> root){
if(root!=null){
printTree(root.left);
System.out.println(root.element);
printTree(root.right);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTree<Integer> tree=new BinaryTree<>();
tree.insert(2);
tree.insert(1);
tree.insert(3);
tree.insert(4);
//tree.printTree();
tree.remove(2);
tree.printTree();
}
}
关于二叉树
最新推荐文章于 2020-07-27 23:07:50 发布