Created
December 27, 2017 18:09
-
-
Save Smakar20/a5f2635a0b206bb4aa588a94ff7b5c5b to your computer and use it in GitHub Desktop.
flattenBfs created by smakar20 - https://repl.it/@smakar20/flattenBfs
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
//Given a binary tree, flatten it to a linked list levelwise. | |
class Tree{ | |
constructor(val){ | |
this.val = val | |
this.left = null | |
this.right = null | |
} | |
insertLeft(val){ | |
this.left = new Tree(val) | |
return this.left | |
} | |
insertRight(val){ | |
this.right = new Tree(val) | |
return this.right | |
} | |
} | |
class Node{ | |
constructor(val){ | |
this.val = val | |
this.next = null | |
} | |
} | |
function flattenBfs(root){ | |
if(!root) return | |
var head = null | |
var tail = null, | |
arr = [root, '--'] | |
for(var node of arr){ | |
if(node == '--' && head) | |
{ | |
print(head) | |
console.log('-----') | |
head = null | |
tail = null | |
arr.push('--') | |
}else{ | |
if(!tail){ | |
tail = new Node(node.val) | |
head = tail | |
}else{ | |
tail.next = new Node(node.val) | |
tail = tail.next | |
} | |
} | |
if(node.left){ | |
arr.push(node.left) | |
} | |
if(node.right){ | |
arr.push(node.right) | |
} | |
} | |
} | |
function print(head){ | |
while(head){ | |
console.log(head.val) | |
head = head.next | |
} | |
} | |
// ----- test ------ | |
var root = new Tree(1) | |
var left = root.insertLeft(2) | |
var right = root.insertRight(3) | |
left.insertLeft(4) | |
left.insertRight(5) | |
right.insertLeft(6) | |
right.insertRight(7) | |
flattenBfs(root) | |
//----output----- | |
/* | |
1 | |
----- | |
2 | |
3 | |
----- | |
4 | |
5 | |
6 | |
7 | |
----- | |
*/ | |
//--------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment