java - 复制没有父引用的树
问题描述
我想创建一个递归方法,它可以复制树并将其作为树而不是节点返回。这是结构:
public class Tree {
Node root;
public Tree(Node root)
this.root = root;
}
public static class Node {
int key;
Node left;
Node right;
public Node(int key, Node left, Node right) {
this.key = key;
this.left = left;
this.right = right;
}
}}
解决方案
public Tree copy() {
if(root == null)
return new Tree(null);
else {
return new Tree(copyRec(root));
}
}
private Node copyRec(Node node) {
if(node != null) {
Node curr = new Node(node.key, null, null);
curr.left = copyRec(node.left);
curr.right = copyRec(node.right);
return curr;
}
return null;
}
推荐阅读
- sql-server - 手动释放由 sp_getapplock 生成的锁
- java - Firebase 云消息传递不起作用 sdk java
- r - 当边多于一个时,visIgraphLayout() 函数会在节点之间重叠边
- ios - DispatchQueue 绑定到确切的线程
- javascript - javascript/React:检查日期是否超过 24 小时
- ios - 从 iOS 文件应用上的位置删除应用
- c# - 修改源项目会更改列表项目?
- r - 如何对分组条形图上所有条形组中的条形进行排序?
- oracle - Hibernate 不返回手动插入的行
- facebook-opengraph - sitefinity 版本 11 打开图