Created
January 15, 2019 03:24
-
-
Save danabrams/20f814f4ea05398d0991127af01dc838 to your computer and use it in GitHub Desktop.
Iterative Tree Traversal
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 Tree { | |
value: Number; | |
left: Tree | null; | |
right: Tree | null; | |
constructor(value: Number) { | |
this.value = value; | |
this.left = null; | |
this.right = null; | |
} | |
insert(value: Number) { | |
let node = this; | |
if (node == null) { | |
this.value = value; | |
return; | |
} else if (node.value == value) { | |
return; | |
} else if (value < node.value) { | |
if (this.left) { | |
this.left.insert(value); | |
} else { | |
this.left = new Tree(value); | |
} | |
return; | |
} else { | |
if (this.right) { | |
this.right.insert(value); | |
} else { | |
this.right = new Tree(value); | |
} | |
return; | |
} | |
} | |
inOrderPrintRecursive() { | |
if (this == null) { | |
return; | |
} else if (this.left) { | |
this.left.inOrderPrintRecursive(); | |
} | |
if (this.value != undefined) { | |
console.log(this.value); | |
} | |
if (this.right) { | |
this.right.inOrderPrintRecursive(); | |
} | |
return; | |
} | |
inOrderPrint() { | |
var current: Tree = this; | |
var ancestors = new Array(); | |
var notStarted = true; | |
while (notStarted || ancestors.length > 0) { | |
notStarted = false; | |
while (current) { | |
ancestors.push(current); | |
current = current.left; | |
} | |
current = ancestors.pop(); | |
console.log(current.value); | |
while (current) { | |
current = current.right | |
ancestors.push(current); | |
} | |
current = ancestors.pop(); | |
} | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here it breaks down a bit! This loop isn't quite right... you're going to shoot very "right-wise" and skip some left "chains" you would've wanted to follow, happy to construct a problem-tree if you like