LintCode - 克隆二叉树(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

深度复制一个二叉树。
给定一个二叉树,返回一个他的 克隆品
样例给定一个二叉树:

    1
   /  \
  2    3
 / \
4   5

返回其相同结构相同数值的克隆二叉树:

    1
   /  \
  2    3
 / \
4   5

思路:递归

/**
 * 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) {
        // Write your code here
        if(root == null){
            return null;
        }
        
        TreeNode node = new TreeNode(root.val);
        node.left = cloneTree(root.left);
        node.right = cloneTree(root.right);
        return node;
    }
}

你可能感兴趣的:(LintCode - 克隆二叉树(普通))