克隆二叉树
来源:互联网 发布:剑三捏脸数据不合法 编辑:程序博客网 时间:2024/06/07 22:59
1.问题描述:深度复制一个二叉树。给定一个二叉树,返回他的一个克隆品。
2.思路:正如样例
给定一个二叉树:
1 / \ 2 3 / \4 5
返回其相同结构相同数值的克隆二叉树:
1 / \ 2 3 / \4 5
建立一个新的二叉树,它的根节点为原二叉树的根节点,再用克隆的函数遍历原二叉树的左子树和右子树即为新二叉树的左子树和右子树
3.代码:
/** * 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) { // Write your code here if(root==NULL) return NULL; TreeNode *newroot=new TreeNode(root->val); newroot->left=cloneTree(root->left); newroot->right=cloneTree(root->right); return newroot; }};
4.感想:在二叉树中的大部分题目都用到了遍历,有了遍历也方便了很多。
0 0
- 二叉树的克隆
- LintCode:克隆二叉树
- 克隆二叉树
- 克隆二叉树
- lintcode,克隆二叉树
- lintcode | 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- LintCode-克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- LintCode 克隆二叉树
- 克隆二叉树-LintCode
- 克隆二叉树ke
- 简单常用滤波算法C语言实现
- 编程之法--字符串包含
- poj 1948 Triangular Pastures
- 动态规划练习一之采药
- 世界坐标转换为NGUI坐标办法举例
- 克隆二叉树
- 数论 欧几里得
- Netpref Test的使用
- 插入排序&希尔排序—思路及实现
- 使用阻塞队列实现生产者-消费者模式——Java实现
- 一篇SSM框架整合友好的文章(二)
- 输出以下的杨辉三角形
- Tomcat servlet工作原理
- LeetCode073 Set Matrix Zeroes