-
Notifications
You must be signed in to change notification settings - Fork 0
/
base-binary-tree.js
87 lines (81 loc) · 1.93 KB
/
base-binary-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict';
/**
* Creates a base binary tree.
* @constructor
*/
var BaseBinaryTree = function () {
/**
* The root of the tree.
* @protected
*/
this.root = undefined;
};
/**
* Performs a pre-order traversal, calling a function on each node.
*
* @param {function} visit A function that takes a node's key.
*/
BaseBinaryTree.prototype.traversePreOrder = function (visit) {
if (!this.root) {
return;
}
var parentStack = [];
parentStack.push(this.root);
do {
var top = parentStack.pop();
visit(top.key);
if (top.right) {
parentStack.push(top.right);
}
if (top.left) {
parentStack.push(top.left);
}
} while (parentStack.length);
};
/**
* Performs a in-order traversal, calling a function on each node.
*
* @param {function} visit A function that takes a node's key.
*/
BaseBinaryTree.prototype.traverseInOrder = function (visit) {
var parentStack = [];
var node = this.root;
while (parentStack.length || node) {
if (node) {
parentStack.push(node);
node = node.left;
} else {
node = parentStack.pop();
visit(node.key);
node = node.right;
}
}
};
/**
* Performs a post-order traversal, calling a function on each node.
*
* @param {function} visit A function that takes a node's key.
*/
BaseBinaryTree.prototype.traversePostOrder = function (visit) {
var parentStack = [];
var node = this.root;
var lastVisitedNode;
while (parentStack.length || node) {
if (node) {
parentStack.push(node);
node = node.left;
} else {
var nextNode = parentStack[parentStack.length - 1];
if (nextNode.right && lastVisitedNode !== nextNode.right) {
// if right child exists AND traversing node from left child, move
// right
node = nextNode.right;
} else {
parentStack.pop();
visit(nextNode.key);
lastVisitedNode = nextNode;
}
}
}
};
module.exports = BaseBinaryTree;