Skip to content

Instantly share code, notes, and snippets.

@danabrams
Created January 15, 2019 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danabrams/20f814f4ea05398d0991127af01dc838 to your computer and use it in GitHub Desktop.
Save danabrams/20f814f4ea05398d0991127af01dc838 to your computer and use it in GitHub Desktop.
Iterative Tree Traversal
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;
}
}
@aaronwhite
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment