克隆二叉树
来源:互联网 发布:sql删除嵌套select 编辑:程序博客网 时间:2024/05/30 23:04
描述:深度复制一个二叉树。给定一个二叉树,返回一个他的 克隆品 。
样例:
给定一个二叉树:
1 / \ 2 3 / \4 5
返回其相同结构相同数值的克隆二叉树:
1 / \ 2 3 / \4
5
解题思路:根据已知信息,相当于把一棵二叉树复制一遍。把它的根节点复制到根节点,把它的左子树与右子树分别复制到新的根节点的左子树与右子树。具体实现方法可以用递归的方法实现。
实现代码:/** * 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* root1 = new TreeNode(root->val); root1->left = cloneTree(root->left); root1->right = cloneTree(root->right); return root1; }};
做题感想:通过这个题可以进一步体会到递归函数的使用方法,以及它的便利之处。
0 0
- 二叉树的克隆
- LintCode:克隆二叉树
- 克隆二叉树
- 克隆二叉树
- lintcode,克隆二叉树
- lintcode | 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- LintCode-克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- 克隆二叉树
- LintCode 克隆二叉树
- 克隆二叉树-LintCode
- 克隆二叉树ke
- 使用map操作对象排序,根据对象字段排序
- cannot resolve symbol
- linux grep用法小白梳理(1)
- 构造方法私有化demo---单例模式
- LeetCode:Longest Palindromic Substring最长回文字符串
- 克隆二叉树
- poj 2418 map的简单使用
- 【编程】【leetcode】303. Range Sum Query
- 设计模式
- 欢迎使用CSDN-markdown编辑器
- caffe深度学习-windows下绘制学习曲线
- C++类模板的特化
- React学习之- (React-JSX-Style)
- LeetCode 8. String to Integer (atoi)