[英]Add method doesn't allow repeating elements - Binary Tree (Java)
我已經編寫了一個代碼來遞歸地在二叉樹中插入一個元素,但是我實現的這個代碼不允許我插入一個重復的元素。 問題是我不知道要在代碼中修改什么,所以我可以插入相同的元素。 例如,我插入 8 作為 2 的孩子,但我也想插入 8 作為 5 的孩子,不同的父母但同一個孩子。 這是我的代碼:
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 的子節點插入,並且 5 也在樹中。 在這些行中:
Node<E> np = searchNode(parent);
Node<E> nce = searchNode(child);
if(nce == null && np != null){
np
將是 5 的節點, nce
將是前 8 的節點。 nce
不是null
因此永遠不會執行if
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.