克隆二叉树
深度复制一个二叉树。
给定一个二叉树,返回一个他的 克隆品 。样例
给定一个二叉树:
返回其相同结构相同数值的克隆二叉树:
标签
二叉树
code
/**
* 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) {
TreeNode* pNewRoot = new TreeNode(root->val);
if(root->left != NULL)
pNewRoot->left = cloneTree(root->left);
if(root->right != NULL)
pNewRoot->right = cloneTree(root->right);
return pNewRoot;
}
return NULL;
}
};