forked from cherryljr/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClone Binary Tree.java
More file actions
52 lines (47 loc) · 1007 Bytes
/
Clone Binary Tree.java
File metadata and controls
52 lines (47 loc) · 1007 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
很简单的一道题目。
使用 分治 的方法即可解决。
/*
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
Tags
Binary Tree
*/
/**
* 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 cloneRoot = new TreeNode(root.val);
cloneRoot.left = cloneTree(root.left);
cloneRoot.right = cloneTree(root.right);
return cloneRoot;
}
}