BST Traversal
BST Traversal
Sample Input
tree = 10
/ \
5 15
/ \ \
2 5 22
/
1
array = []Sample Output
inOrderTraverse: [1, 2, 5, 5, 10, 15, 22] // where the array is the input array
preOrderTraverse: [10, 5, 2, 1, 5, 15, 22] // where the array is the input array
postOrderTraverse: [1, 2, 5, 5, 22, 15, 10] // where the array is the input array// O(n) time | O(n) space
function inOrderTraverse(tree, array) {
if (tree !== null) {
inOrderTraverse(tree.left, array);
array.push(tree.value);
inOrderTraverse(tree.right, array);
}
return array;
}
// O(n) time | O(n) space
function preOrderTraverse(tree, array) {
if (tree !== null) {
array.push(tree.value);
preOrderTraverse(tree.left, array);
preOrderTraverse(tree.right, array);
}
return array;
}
// O(n) time | O(n) space
function postOrderTraverse(tree, array) {
if (tree !== null) {
postOrderTraverse(tree.left, array);
postOrderTraverse(tree.right, array);
array.push(tree.value);
}
return array;
}
exports.inOrderTraverse = inOrderTraverse;
exports.preOrderTraverse = preOrderTraverse;
exports.postOrderTraverse = postOrderTraverse;
Last updated