我做了一个关于在二叉树中插入节点的代码...由于我的add方法中的某些原因,我的代码无法正常工作,请查看每行旁边的注释..这是我的代码,我遇到了问题与..
public class BinarySearchTree<E extends Comparable<? super E>> {
BinaryNode<E> root;
/**
* Constructs an empty binary searchtree.
*/
public BinarySearchTree() {
}
/**
* Inserts the specified element in the tree if no duplicate exists.
* @param x element to be inserted
* @return true if the the element was inserted
*/
public boolean add(E element) {
BinaryNode newNode = new BinaryNode(element);
if(root==null){
root=newNode;
} if (element==this.element){ // element cannot be resolved or is not a field
return false;
} else {
BinaryNode<E> focus = root;
BinaryNode parent;
while(true) {
parent=focus;
if (element < focus.element) { //The operator < is undefined for the argument type(s) E, Object
focus=focus.left;
if (focus==null) {
parent.left=newNode;
return true;
}
} else {
focus=focus.right;
if (focus==null) {
parent.right=newNode; //
}
return true;
}
}
}
}
static class BinaryNode<E> {
E element;
BinaryNode<E> left;
BinaryNode<E> right;
private BinaryNode(E element) {
this.element = element;
}
}
}
如何纠正我的错误?
我的代码是否合适?是否需要更改?
谢谢
答案 0 :(得分:0)
我更改了你的代码,你比较元素少于focus.element,我已经把元素.compareTo(focus.element)&lt; 0,是比较事物而不是整数的方法
public class BinarySearchTree<E extends Comparable<? super E>> {
BinaryNode<E> root;
/**
* Constructs an empty binary searchtree.
*/
public BinarySearchTree() {
}
/**
* Inserts the specified element in the tree if no duplicate exists.
* @param element to be inserted
* @return true if the the element was inserted
*/
public boolean add(E element) {
BinaryNode newNode = new BinaryNode(element);
if(root==null){
root=newNode;
System.out.println("root");
} if (element==root.element){ // element cannot be resolved or is not a field
return false;
} else {
BinaryNode<E> focus = root;
BinaryNode parent;
while(true) {
parent=focus;
if (element.compareTo(focus.element) < 0) { //Here is my change!!! The operator < is undefined for the argument type(s) E, Object
focus=focus.left;
System.out.println("left");
if (focus==null) {
parent.left=newNode;
return true;
}
} else {
focus=focus.right;
System.out.println("right");
if (focus==null) {
parent.right=newNode; //
}
return true;
}
}
}
}
static class BinaryNode<E> {
E element;
BinaryNode<E> left;
BinaryNode<E> right;
private BinaryNode(E element) {
this.element = element;
}
}
}