如何深度复制二叉树? [英] How to deep copy a Binary Tree?

查看:138
本文介绍了如何深度复制二叉树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自己的Node类在Java中实现树结构。但我很困惑如何做一个深拷贝复制树。

I would like using my own Node class to implement tree structure in Java. But I'm confused how to do a deep copy to copy a tree.

我的Node类是这样的:

My Node class would be like this:

public class Node{
private String value;
private Node leftChild;
private Node rightChild;
....

我是递归的新手,所以有任何代码我可以学习?谢谢!

I'm new to recursion, so is there any code I can study? Thank you!

推荐答案

试试

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

这篇关于如何深度复制二叉树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆