如何深度复制二叉树?
我想使用自己的Node类在Java中实现树结构。 但我很困惑如何做一个深拷贝来复制树。
我的Node类是这样的:
public class Node{ private String value; private Node leftChild; private Node rightChild; ....
我是递归的新手,所以我可以学习任何代码吗? 谢谢!
尝试
class Node { private String value; private Node left; private Node right; public Node(String value, Node left, Node right) { this.value = value; ... } Node copy() { Node left = null; Node right = null; if (this.left != null) { left = this.left.copy(); } if (this.right != null) { right = this.right.copy(); } return new Node(value, left, right); } }
你可以使用这样的东西。 它将首先通过旧的树深度并创建它的副本。
private Tree getCopyOfTree(oldTree) { Tree newTree = new Tree(); newTree.setRootNode(new Node()); copy(oldTree.getRootNode(), newTree.getRootNode()) return newTree; } private void copy(Node oldNode, Node newNode) { if (oldNode.getLeftChild != null) { newNode.setLeftChild(new Node(oldNode.getLeftChild())); copy(oldNode.getLeftChild, newNode.getLeftChild()); } if (oldNode.getRightChild != null) { newNode.setRightChild(new Node(oldNode.getRightChild())); copy(oldNode.getRightChild, newNode.getRightChild()); } }
我喜欢上面的Evgeniy Dorofeev的答案,但有时你可能无法为类型Node
添加方法,因为你可能不拥有它。 在那种情况下(这是在c#中):
public static TreeNode CopyTree(TreeNode originalTreeNode) { if (originalTreeNode == null) { return null; } // copy current node's data var copiedNode = new TreeNode(originalTreeNode.Data); // copy current node's children foreach (var childNode in originalTreeNode.Children) { copiedNode.Children.Add(CopyTree(childNode)); } return copiedNode; }
使用预订遍历以递归方式执行此操作。
public static Node CopyTheTree(Node root) { if (root == null) { return null; } Node newNode = new Node(null, null, root.Value); newNode.Left= CopyTheTree(root.Left); newNode.Right= CopyTheTree(root.Right); return newNode; }
不确定但尝试使用树的邮件订单遍历并为您遍历的每个节点创建新节点。 您可能需要堆栈来存储您创建的节点以生成左右子链接。
public static TreeNode copy( TreeNode source ) { if( source == null ) return null; else return new TreeNode( source.getInfo( ), copy( source.getLeft( ) ), copy( source.getRight( ) ) ); }
/ 当然。 抱歉耽搁了。 无论如何……任何递归方法都有一个基本案例,以及一个或多个递归案例。 在这个例子中,第一行是显而易见的……如果参数’source’的参数为null(因为它最终计算为了结束方法的操作),它将返回null; 如果不是,则启动递归情况。 在这种情况下,一旦递归完成,您将返回整个复制的树。 使用’new’运算符,指示在遍历期间每次访问树的各个节点时TreeNode的实例化,通过递归调用’copy’发生,其参数成为对左右TreeNodes的引用(如果有的话)是任何)。 一旦source在每个参数中变为null,就会启动基本情况,将递归堆栈释放回原始调用“copy”,这是原始树的根的副本。 /
- Maven放置在JAR文件中的POM文件的重要性是什么,它是否被任何东西使用?
- RMI注册表问题:使用“file:”URL方案绑定代码库时,rmiregistry可能会导致意外exception
- @ManyToOne和@BatchSize
- 更改Eclipse Getters Setters语法
- 是否有任何OSS库或纸张执行单声道位图的矢量路径跟踪?
- 如何使HK2 ServiceLocator使用来自它桥接的ServiceLocator的Singleton服务实例?
- 实现并发LinkedHashMap
- 如何使用MUnit在Mule Flow中模拟Java组件
- spring boot – 如何在HTTP控制器处理程序中避免“无法实例化:指定的类是一个接口”?