3693 · Clone N-branch Tree
Algorithms
Medium
Accepted Rate
84%
Description
Solution4
Notes
Discuss2
Leaderboard
Record
Description
Given a root of an N-branch tree, return a deep copy (clone) of the tree.
Deep copy
A reference object consists, in general, of two parts: a named Handle, which is what we call a declaration (e.g., a variable), and an internal (unnamed) object, which is the internal object named Handle. It is allocated in the Managed Heap and is typically created by the New method of the newly referenced object.
A deep copy is one in which the source and copy objects are independent of each other, so that changes to either object do not affect the other.
Each node in the n-branch tree contains a value and a list of its children:
java
python
cpp
class NBranchTree {
public:
int val;
vector<NBranchTree*> children;
NBranchTree(int _val) {
val = _val;
}
NBranchTree(int _val, vector<NBranchTree*> _children) {
val = _val;
children = _children;
}
};
N-Branch-Tree input serialization is represented in their level order traversal, each group of children is separated by the & (See examples).
The depth of the n-ary tree is less than or equal to 1000.
Example
Example 1
Input
root = [1,&,3,2,4,&,5,6]
Output
[1,&,3,2,4,&,5,6]
Explanation
The N-branch tree represented by root = [1,&,3,2,4,&,5,6] is shown below:
1
/ | \
3 2 4
/\
5 6
Example 2
Input
root = [1,&,2,3,4,5,&,#,&,6,7,&,8,&,9,10,&,#,&,11,&,12,&,13,&,#,&,14]
Output
[1,&,2,3,4,5,&,#,&,6,7,&,8,&,9,10,&,#,&,11,&,12,&,13,&,#,&,14]
Explanation
The N-branch tree represented by root = [1,&,2,3,4,5,&,#,&,6,7,&,8,&,9,10,&,#,&,11,&,12,&,13,&,#,&,14] is shown below:
2 - 1
/ | \
3 4 5
/\ | /\
6 7 8 9 10
| | |
11 12 13
|
14
ps. Root node is 1.
Tags
Related Problems
137
Clone Graph
Medium
3690
Clone Binary Tree II
Medium
解法1:
/**
* Definition of NBranchTree:
* class NBranchTree {
* public:
* int val;
* vector<NBranchTree *> children;
* NBranchTree(int _val) {
* this->val = val;
* }
* NBranchTree(int _val, vector<NBranchTree*> _children) {
* val = _val;
* children = _children;
* }
* };
*/
class Solution {
public:
/**
* @param root: The root node of a n-branch tree.
* @return: The cloned tree.
*/
NBranchTree* cloneTree(NBranchTree *root) {
if (!root) return NULL;
NBranchTree *copyRoot = new NBranchTree(root->val);
copyRoot->children.resize(root->children.size());
for (int i = 0; i < root->children.size(); i++) {
copyRoot->children[i] = cloneTree(root->children[i]);
}
return copyRoot;
}
};