gpt4 book ai didi

java - 复制没有父引用的树

转载 作者:行者123 更新时间:2023-12-02 09:44:59 24 4
gpt4 key购买 nike

我想创建一个递归方法,它可以复制树并将其作为树而不是节点返回。这是结构:

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;
}

关于java - 复制没有父引用的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56734218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com