上一篇文章写了使用java实现顺序存储的二叉树,这次接着使用java实现链式存储的二叉树:
首先创建一个结点类TreeNode<E>:
package com.linkedTree;
public class TreeNode<E> {
private E item;
private TreeNode<E> leftChild;
private TreeNode<E> rightChild;
public TreeNode(E item){
this(item,null,null);
}
public TreeNode(E item, TreeNode<E> l , TreeNode<E> r){
this.item = item;
this.leftChild = l;
this.rightChild = r;
}
public TreeNode<E> getRightChild() {
return rightChild;
}
public void setRightSibling(TreeNode<E> rightChild) {
this.rightChild = rightChild;
}
public TreeNode<E> getLeftChild() {
return leftChild;
}
public void setLeftSibling(TreeNode<E> leftChild) {
this.leftChild = leftChild;
}
public E getItem() {
return item;
}
public void setItem(E item) {
this.item = item;
}
@Override
public int hashCode() {//重写hashCode和equals方法
final int prime = 31;
int result = 1;
result = prime * result + ((item == null) ? 0 : item.hashCode());
result = prime * result + ((leftChild == null) ? 0 : leftChild.hashCode());
result = prime * result + ((rightChild == null) ? 0 : rightChild.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TreeNode<?> other = (TreeNode<?>) obj;
if (item == null) {
if (other.item != null)
return false;
} else if (!item.equals(other.item))
return false;
if (leftChild ==