Created
October 15, 2016 23:15
-
-
Save nyk0r/b13f0aaffdb5d98b91b58832b37a1f83 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 BinaryNode<T> { | |
public constructor(public value: T, public left: BinaryNode<T> = null, public right: BinaryNode<T> = null) {} | |
} | |
interface INodeProcessor<T> { | |
(value: T): void; | |
} | |
interface IBinaryNodeTraversal<T> { | |
(node: BinaryNode<T>, processor: INodeProcessor<T>): void; | |
} | |
function traverseInOrderRecursive<T>(node: BinaryNode<T>, processor: INodeProcessor<T>): void { | |
if (node.left) { | |
traverseInOrderRecursive(node.left, processor); | |
} | |
processor(node.value); | |
if (node.right) { | |
traverseInOrderRecursive(node.right, processor); | |
} | |
} | |
function traverseInOrderIterative<T>(node: BinaryNode<T>, processor: INodeProcessor<T>): void { | |
class NodeProccessing { | |
public constructor(public node: BinaryNode<T>, public leftProcessed: boolean = false, public valueProcessed: boolean = false, public rightProcessed = false) {} | |
} | |
let stack: NodeProccessing[] = [ new NodeProccessing(node) ]; | |
while(stack.length !== 0) { | |
let frame = stack[stack.length - 1]; | |
if (frame.node.left && !frame.leftProcessed) { | |
frame.leftProcessed = true; | |
stack.push(new NodeProccessing(frame.node.left)); | |
continue; | |
} | |
if (!frame.valueProcessed) { | |
frame.valueProcessed = true; | |
processor(frame.node.value); | |
} | |
if (frame.node.right && !frame.rightProcessed) { | |
frame.rightProcessed = true; | |
stack.push(new NodeProccessing(frame.node.right)); | |
continue; | |
} | |
stack.pop(); | |
} | |
} | |
function binaryTreeToArray<T>(tree: BinaryNode<T>, traversal: IBinaryNodeTraversal<T>): T[] { | |
let result: T[] = []; | |
let processor: INodeProcessor<T> = v => result.push(v); | |
traversal(tree, processor); | |
return result; | |
} | |
let tree = new BinaryNode( | |
5, | |
new BinaryNode( | |
3, | |
new BinaryNode(2, new BinaryNode(1), null), | |
new BinaryNode(4, null, null) | |
), | |
new BinaryNode( | |
8, | |
new BinaryNode(7, new BinaryNode(6), null), | |
new BinaryNode(9, null, new BinaryNode(10)) | |
) | |
); | |
console.log(binaryTreeToArray(tree, traverseInOrderRecursive)); | |
console.log(binaryTreeToArray(tree, traverseInOrderIterative)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment