Last active
June 13, 2018 00:06
-
-
Save pinkmomo027/a7d8c90593a16d101ec41171c054a3e1 to your computer and use it in GitHub Desktop.
Clone Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value) { | |
this.value = value; | |
this.children = []; | |
} | |
add(child) { | |
this.children.push(child); | |
} | |
print(level=0) { | |
let indent = ""; | |
for (let i = 0; i < level * 2; i++) { | |
indent += " "; | |
} | |
process.stdout.write(`${indent}value : ${this.value} \n`); | |
if(this.children.length > 0) { | |
process.stdout.write(`${indent}children ↓↓ \n`); | |
this.children.forEach(child => { | |
child.print(level+1); | |
}); | |
} | |
} | |
} | |
let root = new Node(0); | |
let l1 = new Node(10); | |
let l2 = new Node(100); | |
let l3 = new Node(500); | |
root.add(l1); | |
root.add(l2); | |
root.add(l3); | |
let p1 = new Node('A'); | |
let p2 = new Node('B'); | |
l1.add(p1); | |
l1.add(p2); | |
let x1 = new Node('X'); | |
l3.add(x1); | |
let z1 = new Node("horse"); | |
x1.add(z1); | |
root.print(); | |
function clone(node) { | |
let newNode = new Node(node.value); | |
node.children.forEach( n => { | |
newNode.add(clone(n)); | |
}); | |
return newNode; | |
} | |
let cloned = clone(root); | |
console.log("------------BELOW IS THE CLONED TREE--------------"); | |
cloned.print(); | |
// value : 0 | |
// children ↓↓ | |
// value : 10 | |
// children ↓↓ | |
// value : A | |
// value : B | |
// value : 100 | |
// value : 500 | |
// children ↓↓ | |
// value : X | |
// children ↓↓ | |
// value : horse | |
// ------------BELOW IS THE CLONED TREE-------------- | |
// value : 0 | |
// children ↓↓ | |
// value : 10 | |
// children ↓↓ | |
// value : A | |
// value : B | |
// value : 100 | |
// value : 500 | |
// children ↓↓ | |
// value : X | |
// children ↓↓ | |
// value : horse | |
// [Finished in 0.1s] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment