375. Clone Binary Tree【LintCode java】
阿新 • • 發佈:2018-07-14
bin ret tree right ini struct param style esc
Description
For the given binary tree, return a deep copy of it.
Example
Given a binary tree:
1
/ 2 3
/ 4 5
return the new binary tree with same structure and same value:
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 new_root = new TreeNode(root.val);
new_root.left = cloneTree(root.left);
new_root.right = cloneTree(root.right);
return new_root;
}
}
375. Clone Binary Tree【LintCode java】