我在理解BinaryTree ADT时遇到了问题,尤其是插入方法。
我在互联网上找到的大多数实现都有两个参数,第一个是现有节点,第二个是要插入的数据,其工作方式与#34相同;如果数据小于节点数据,则将其添加为左节点或左侧节点的递归调用插入,否则在右侧执行相同的操作。
普通二叉树(不是搜索binaryTree)真的需要这种比较吗?因为我想实现一个通用树,这些值可能不那么容易比较。
树界面
public interface IBinaryTree<E> {
public IBinaryTreeNode<E> getRoot();
public Boolean isEmpty();
public void insert(E data);
}
TreeNode接口
public interface IBinaryTreeNode<E> {
public IBinaryTreeNode<E> getLeftNode();
public IBinaryTreeNode<E> getRightNode();
public E getData();
public void setData(E data);
public void setLeftNode(IBinaryTreeNode<E> node);
public void setRightNode(IBinaryTreeNode<E> node);
public IBinaryTreeNode<E> inorderFind(E data);
public IBinaryTreeNode<E> preorderFind(E data);
public IBinaryTreeNode<E> postorderFind(E data);
}
TreeNode实现
public class BinaryTreeNode<E> implements IBinaryTreeNode<E> {
private IBinaryTreeNode<E> left;
private IBinaryTreeNode<E> right;
E data;
@Override
public IBinaryTreeNode<E> getLeftNode() {
return left;
}
@Override
public IBinaryTreeNode<E> getRightNode() {
return right;
}
@Override
public E getData() {
return data;
}
@Override
public void setData(E data) {
this.data = data;
}
@Override
public void setLeftNode(IBinaryTreeNode<E> node) {
left = node;
}
@Override
public void setRightNode(IBinaryTreeNode<E> node) {
right = node;
}
// Inorder search (Left tree --> Node --> Right tree)
@Override
public IBinaryTreeNode<E> inorderFind(E data) {
if(left != null){
IBinaryTreeNode<E> leftResult = this.left.inorderFind(data);
if(leftResult != null)
return leftResult;
}
if(this.data.equals(data))
return this;
if(right != null){
IBinaryTreeNode<E> rightResult = this.right.inorderFind(data);
if(rightResult != null)
return rightResult;
}
return null;
}
// Preorder search (Node --> Left tree --> Right tree)
@Override
public IBinaryTreeNode<E> preorderFind(E data) {
if(this.data.equals(data))
return this;
if(left != null){
IBinaryTreeNode<E> leftResult = left.preorderFind(data);
if(leftResult != null)
return leftResult;
}
if(right != null){
IBinaryTreeNode<E> rightResult = right.preorderFind(data);
if(rightResult != null)
return rightResult;
}
return null;
}
// Postorder search (Left tree --> Right tree --> Node)
@Override
public IBinaryTreeNode<E> postorderFind(E data) {
if(left != null){
IBinaryTreeNode<E> leftResult = left.preorderFind(data);
if(leftResult != null)
return leftResult;
}
if(right != null){
IBinaryTreeNode<E> rightResult = right.preorderFind(data);
if(rightResult != null)
return rightResult;
}
if(this.data.equals(data))
return this;
return null;
}
}
最后是树实现
public class BinaryTree<E extends Object> implements IBinaryTree<E> {
IBinaryTreeNode<E> root;
int size;
public BinaryTree(IBinaryTreeNode<E> node){
this.root = node;
size++;
}
@Override
public IBinaryTreeNode<E> getRoot() {
return root;
}
@Override
public Boolean isEmpty() {
return (size == 0);
}
@Override
public void insert(E data) {
}
}