深度复制一个二叉树。
给定一个二叉树,返回一个他的 克隆品 。
题目链接
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree
* @return root of new tree
*/
public TreeNode cloneTree(TreeNode root) {
if(root == null) return null;
TreeNode clone = new TreeNode(root.val);
TreeNode temp = clone;
copy(root, temp);
return clone;
}
private void copy(TreeNode root, TreeNode temp) {
if(root.left != null) {
TreeNode left = new TreeNode(root.left.val);
temp.left = left;
copy(root.left, temp.left);
}
if(root.right != null) {
TreeNode right = new TreeNode(root.right.val);
temp.right = right;
copy(root.right, temp.right);
}
}
}