克隆二叉树
题目
深度复制一个二叉树。
给定一个二叉树,返回一个他的 克隆品 。样例
给定一个二叉树:
返回其相同结构相同数值的克隆二叉树:
题解
/**
* 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 root;
}
TreeNode result = new TreeNode(root.val);
result.left = cloneTree(root.left);
result.right = cloneTree(root.right);
return result;
}
}
Last Update 2016.9.13