Last active
January 9, 2019 12:13
-
-
Save sharmaabhinav/0fc95275c497c3cf59dcb50721a5a5d3 to your computer and use it in GitHub Desktop.
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 (val) { | |
this.val = val | |
this.children = [] | |
} | |
addChildren (val) { | |
const node = new Node(val) | |
this.children.push(node) | |
return node | |
} | |
} | |
class Tree { | |
constructor (val) { | |
this.root = null | |
} | |
addNode (parent, val) { | |
if (parent === null) { | |
this.root = new Node(val) | |
return this.root | |
} | |
const node = this.findNode(this.root, parent) | |
return node.addChildren(val) | |
} | |
findNode (current, start) { | |
if (current === start) { | |
return current | |
} | |
for(var index = 0; index < current.children.length; index++) { | |
const node = this.findNode(current.children[index], start) | |
if (node) { | |
return node | |
} | |
} | |
} | |
// print in breath first manner | |
print () { | |
console.log('------') | |
console.log('------') | |
} | |
} | |
var tree = new Tree () | |
var t1 = tree.addNode(null, 1) | |
var t2 = tree.addNode(t1, 2) | |
var t3 = tree.addNode(t1, 3) | |
var t4 = tree.addNode(t1, 4) | |
var t5 = tree.addNode(t2, 5) | |
var t6 = tree.addNode(t2, 6) | |
console.log(t1) | |
console.log(t2) | |
console.log(t3) | |
console.log(t4) | |
console.log(t5) | |
console.log(t6) | |
console.log(tree.print()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment