添加方法不允许重复元素 - 二叉树 (Java)
Add method doesn't allow repeating elements - Binary Tree (Java)
我写了一个代码来递归地在二叉树中插入一个元素,但是我实现的这个代码不允许我插入重复的元素。问题是我不知道要在代码中修改什么以便插入相同的元素。例如,我插入 8 作为 2 的 child,但我也想插入 8 作为 5 的 child,不同的 parents 但相同的 child。这是我的代码:
public class BT<E> {
private Node<E> root;
private class Node<E>{
private E data;
private Node<E> left;
private Node<E> right;
public Node(E data){
this.data = data;
}
}
public boolean add(E child, E parent){
Node<E> nc = new Node<>(child);
if(isEmpty() && parent == null){
root = nc;
return true;
}
Node<E> np = searchNode(parent);
Node<E> nce = searchNode(child);
if(nce == null && np != null){
if(np.left == null){
np.left = nc;
return true;
}
else if(np.right == null){
np.right = nc;
return true;
}
}
return false;
}
private Node<E> searchNode(E data){
return searchNode(data, root);
}
private Node<E> searchNode(E data, Node<E> p){
if(p == null)
return p;
/*else if(p.data.equals(data))
return p;*/
else{
Node<E> nl = searchNode(data, p.left);
if(nl != null) return nl;
return searchNode(data, p.right);
}
}
}
假设 8 已经作为 2 的 child 插入,并且 5 也在树中。在这些行中:
Node<E> np = searchNode(parent);
Node<E> nce = searchNode(child);
if(nce == null && np != null){
np
将是5的节点,nce
将是前8的节点。nce
不是null
所以if
语句永远不会执行。
我写了一个代码来递归地在二叉树中插入一个元素,但是我实现的这个代码不允许我插入重复的元素。问题是我不知道要在代码中修改什么以便插入相同的元素。例如,我插入 8 作为 2 的 child,但我也想插入 8 作为 5 的 child,不同的 parents 但相同的 child。这是我的代码:
public class BT<E> {
private Node<E> root;
private class Node<E>{
private E data;
private Node<E> left;
private Node<E> right;
public Node(E data){
this.data = data;
}
}
public boolean add(E child, E parent){
Node<E> nc = new Node<>(child);
if(isEmpty() && parent == null){
root = nc;
return true;
}
Node<E> np = searchNode(parent);
Node<E> nce = searchNode(child);
if(nce == null && np != null){
if(np.left == null){
np.left = nc;
return true;
}
else if(np.right == null){
np.right = nc;
return true;
}
}
return false;
}
private Node<E> searchNode(E data){
return searchNode(data, root);
}
private Node<E> searchNode(E data, Node<E> p){
if(p == null)
return p;
/*else if(p.data.equals(data))
return p;*/
else{
Node<E> nl = searchNode(data, p.left);
if(nl != null) return nl;
return searchNode(data, p.right);
}
}
}
假设 8 已经作为 2 的 child 插入,并且 5 也在树中。在这些行中:
Node<E> np = searchNode(parent);
Node<E> nce = searchNode(child);
if(nce == null && np != null){
np
将是5的节点,nce
将是前8的节点。nce
不是null
所以if
语句永远不会执行。