【发布时间】:2011-04-20 19:49:15
【问题描述】:
我正在尝试从 2 个已知 BST 的交集创建一个新的 BST。在第二种情况下,我在 intersect2 方法中得到 NullPointerException,在“cur3.item.set_account_id(cur1.item.get_accountid()+ cur2.item.get_accountid());”行。我知道当您尝试取消引用变量而不初始化它时会出现错误,但我认为我正在初始化它?我不太确定。我将不胜感激。
public static Bst<Customer> intersect(Bst<Customer> a, Bst<Customer> b){
return( intersect2(a.root, b.root));
}
public static Bst<Customer> intersect2(BTNode<Customer> cur1, BTNode<Customer> cur2){
Bst<Customer> result = new Bst<Customer>();
// 1. both empty -> true
if (cur1==null && cur2==null){
result=null;
}
// 2. both non-empty -> compare them
else if (cur1!=null && cur2!=null) {
BTNode<Customer> cur3 = new BTNode<Customer>();
cur3.item.set_account_id(cur1.item.get_accountid()+ cur2.item.get_accountid());
result.insert(cur3.item);
intersect2(cur1.left, cur2.left);
intersect2(cur1.right, cur2.right);
}
// 3. one empty, one not -> false
else if (cur1==null ||cur2==null){
BTNode<Customer> cur3 = new BTNode<Customer>();
cur3.item=null;
intersect2(cur1.left, cur2.left);
intersect2(cur1.right, cur2.right);
}
return result;
}
这是问题的图片:
【问题讨论】:
-
为什么不直接做
Bst<Customer> intersection = new Bst<Customer>(); for(Customer c : a) if(b.contains(c)) intersection.add(c); -
对不起,但我没有听懂你想说的话。我的目标是通过在两个给定树都有子节点的级别添加节点来创建第三棵树。新树的元素是通过添加 Customer 对象的属性之一来决定的。
-
那么,如果两棵树有相同的客户,但它位于三个 a 的第三个“级别”和树 b 的第四个“级别”,它不会包含在您的交集中?
-
如果树 a 只有 3 层,那么结果树将只有 3 层。只有在树 a 也至少有 4 层时,才会将树 b 的第四层的客户纳入计算。现在是不是更有意义了?
-
不,它没有。为什么树中元素的内部位置对交叉点很重要?树的用户不应该知道(或关心)元素在树中的位置,只是它们存在并且可以在合理的时间内(在本例中为 lg n)检索到。