【发布时间】:2011-04-20 10:22:49
【问题描述】:
嘿,所以我想创建一个新树,它基本上是两个给定二叉搜索树的交集(交集的数学定义)。我有一种方法可以打印出树的特定级别的所有节点,我有一种方法可以找出树的深度。到目前为止,我正在粘贴我的工作,尽管它不完整并且我被困在logic.Help 将不胜感激。
public static Bst<Customer> intersect (Bst<Customer> a, Bst<Customer> b){
Bst<Customer> result = new Bst<Customer>();
BTNode<Customer> cur1;
BTNode<Customer> cur2;
BTNode<Customer> cur3;
cur1=a.root;
cur2=b.root;
cur3=result.root;
int Resultdepth;
if(a.maxDepth()<b.maxDepth())
Resultdepth=a.maxDepth();
else
Resultdepth=b.maxDepth();
if(cur1==null || cur2==null){ // Handeling the root case intially
result = null;
}
else
cur3.item.set_account_id(cur1.item.get_accountid()+ cur2.item.get_accountid());
cur1=cur1.left;
cur2=cur2.left;
cur3=cur3.left;
while(<some check>){
}
return result;
}
public int maxDepth(){
return mD(root);
}
int mD(BTNode<E> node){
if (node==null) {
return(0);
}
else {
int lDepth = mD(node.left);
int rDepth = mD(node.right);
// use the larger + 1
return(Math.max(lDepth, rDepth) + 1);
}
}
// for printing the nodes at a particular level and giving the starting level
public void PrintAt(BTNode<E> cur, int level, int desiredLevel) {
if (cur == null) {
return;
}
if (level == desiredLevel) {
System.out.print(cur.item.toString() + "");
}
else {
PrintAt(cur.left, level+1, desiredLevel);
PrintAt(cur.right, level+1, desiredLevel);
}
}
【问题讨论】:
-
我在您的代码中没有看到任何与“交集”相关的内容...
-
对不起,我忘了把我的代码放进去。它现在在那里。
-
我强烈建议您不要尝试使用诸如
cur1, cur2, cur3等离散变量来硬编码任何最大深度。您的解决方案必须适用于所有 情况。您会发现一般情况的解决方案也比做出假设的解决方案更简单。
标签: java algorithm binary-search-tree