@Override publicbooleanequals(Object o){ if (this == o) returntrue; if (o == null || getClass() != o.getClass()) returnfalse;
TreeNode<?> treeNode = (TreeNode<?>) o;
if (!data.equals(treeNode.data)) returnfalse; if (!parent.equals(treeNode.parent)) returnfalse; if (!left.equals(treeNode.left)) returnfalse; return right.equals(treeNode.right); }
@Override publicinthashCode(){ int result = data.hashCode(); result = 31 * result + parent.hashCode(); result = 31 * result + left.hashCode(); result = 31 * result + right.hashCode(); return result; } }
// 根节点 private TreeNode<E> root;
publicLookBinTree(E root){ this.root = new TreeNode<>(root); }
/** * 添加节点 * * @param data * @return */ publicvoidadd(E data){ // 根节点为空,则为根节点 if (root == null) { root = new TreeNode<>(data); } else { TreeNode<E> current = root; TreeNode<E> parent = null; // 从根节点往下搜索,找到合适的叶子节点 int cmp = 0; do { parent = current; cmp = data.compareTo(parent.data); if (cmp > 0) { // 新节点大于当前节点 current = current.right; } else { // 新节点小于当前节点 current = current.left; } } while (current != null); // 创建新节点 TreeNode<E> newNode = new TreeNode<>(data, parent, null, null); if (cmp > 0) { parent.right = newNode; } else { parent.left = newNode; }