java - 将二叉树附加到另一个二叉树
问题描述
该方法将树T1和T2的内部结构附加为叶子引用p的左右子树,并将T1和T2重置为空树;如果 p 不是叶子,则会发生错误情况。
public void attach(Node p, BinaryTree t1, BinaryTree t2) {
if (p.left == null) { //logic error??
p.left = t1.root;
t1.root = null;
}
if (p.right == null) {
p.right = t2.root;
t1.root = null;
}
else
System.out.print("is not leaf");
}
解决方案
不要删除 t1 和 t2 根,当您将 t1.root 分配给 p.left 并将 t2.root 分配给 p.right 时,任务就完成了。
这是因为 java 使用 t1 和 t2 对象来引用 p.left 和 p.right
public void attach(Node p, BinaryTree t1, BinaryTree t2){
if(p.left ==null){
p.left=t1.root;
}
if(p.right==null){
p.right=t2.root;
}
else
System.out.print("is not leaf");
}
推荐阅读
- batch-file - 如何避免批量等号拆分
- javascript - 如何在golang中顺序处理并发请求?
- c# - 如何获取特定类型的基本类型
- ios - 手动将 GoogleTagManager 更新到 7.1.1 后崩溃
- python-3.x - 将 Jupyter 笔记本转换为 MS Word 文档 .doc?
- php - 内容(); 不在自定义模板中工作
- wordpress - 为什么我的 wordpress 网站速度很慢并且加载时间很长?
- docker - Is there a well maintained docker image with gcloud installed in it?
- junit - 缺少的步骤 - Junit - Cucumber
- javascript - 如何在保留状态的同时复制组件?