LintCode 375: Clone Binary Tree

本文介绍了一种通过深度优先搜索(DFS)算法来实现二叉树的深拷贝方法。具体而言,该方法递归地复制了原始二叉树的每个节点,创建了一个与原树结构完全相同的新树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Clone Binary Tree
    中文English
    For the given binary tree, return a deep copy of it.

Example
Example 1:

Input: {1,2,3,4,5}
Output: {1,2,3,4,5}
Explanation:
The binary tree is look like this:
1
/
2 3
/
4 5
Example 2:

Input: {1,2,3}
Output: {1,2,3}
Explanation:
The binary tree is look like this:
1
/
2 3
Notice
You’d better not just return root to solve the problem.

解法1:DFS
代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree
     * @return: root of new tree
     */
    TreeNode * cloneTree(TreeNode * root) {
        if (!root) return NULL;
        TreeNode * copyRoot = new TreeNode(root->val);
        copyRoot->left = cloneTree(root->left);
        copyRoot->right = cloneTree(root->right);
        return copyRoot;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值