LintCode 克隆二叉树
来源:互联网 发布:js 选择日期 时间 编辑:程序博客网 时间:2024/05/22 14:11
题目描述:
深度复制一个二叉树。
给定一个二叉树,返回一个他的 克隆品 。
您在真实的面试中是否遇到过这个题? Yes
样例
给定一个二叉树:
1
/ \
2 3
/ \
4 5
返回其相同结构相同数值的克隆二叉树:
1
/ \
2 3
/ \
4 5
思路分析:
dfs
ac代码:
/** * 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 *ans; void dfs(TreeNode *root,TreeNode *ans) { if(!root) return ; if(root->left!=NULL) { TreeNode *r=new TreeNode(root->left->val); ans->left=r; dfs(root->left,ans->left); } else { ans->left=NULL; dfs(root->left,ans->left); } if(root->right!=NULL) { TreeNode *r=new TreeNode(root->right->val); ans->right=r; dfs(root->right,ans->right); } else { ans->right=NULL; dfs(root->right,ans->right); } } TreeNode* cloneTree(TreeNode *root) { // Write your code here if(!root) return NULL; ans=new TreeNode(root->val); dfs(root,ans); return ans; }};
0 0
- LintCode:克隆二叉树
- lintcode,克隆二叉树
- lintcode | 克隆二叉树
- LintCode-克隆二叉树
- LintCode 克隆二叉树
- 克隆二叉树-LintCode
- Lintcode 克隆二叉树
- LintCode 克隆二叉树
- lintcode -- 克隆二叉树
- lintcode:克隆二叉树
- 克隆二叉树-LintCode
- lintcode 375 克隆二叉树
- [LintCode]375.克隆二叉树
- lintcode——克隆二叉树
- LintCode算法题解——判断数独是否合法、平面列表、克隆二叉树、序列排号
- 二叉树的克隆
- 克隆二叉树
- 克隆二叉树
- coreseek搜索系统建立指南
- Uva-1633 Dyslexic Gollum(状压DP)
- Python学习之列表和元组
- windows下GitHub的SSH key配置
- 将二叉查找树转换成双链表
- LintCode 克隆二叉树
- 关于诊断网络问题
- L1-030. 一帮一 java
- "as" in Swift
- 【React Native开发】
- socket 简单理解
- js中如何通过单击事件获取当前对象,并传递当前对象到函数中?
- 【LeetCode】 61. Rotate List C语言
- Matlab 图像压缩编码—代码内容