Skip to content

Instantly share code, notes, and snippets.

@imjul1an
Last active June 3, 2018 19:08
Show Gist options
  • Save imjul1an/d1ee138d99f08e2de67cd0be19fbe3db to your computer and use it in GitHub Desktop.
Save imjul1an/d1ee138d99f08e2de67cd0be19fbe3db to your computer and use it in GitHub Desktop.
Traversing Pre-order BST
/* input: [2,3,4,5,2,3,4]
2
/ \
3 4
/ \ / \
5 2 3 4
*/
const input = {
val: 2,
right: {
val: 4,
right: { val: 4, right: null, left: null },
left: { val: 3, right: null, left: null }
},
left: {
val: 3,
right: { val: 2, right: null, left: null },
left: { val: 5, right: null, left: null }
}
};
/**
* Pre-order BST Traversal (Root->Left->Right). Recursive solution.
* @param {TreeNode} root
* @param {number[]} acc
* @return {number[]}
*/
const preorderTraversalRecursive = (root, acc = []) => {
if (!!root) {
acc.push(root.val);
if (root.left) preorderTraversal(root.left, acc);
if (root.right) preorderTraversal(root.right, acc);
}
return acc;
};
/**
* Pre-order BST Traversal (Root->Left->Right). Iterative solution.
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversalIterative = (root) => {
/**
* Algorithm:
* 1. Create an empty stack [];
* 2. Do while stack is not empty:
* 2.1. Pop an item from stack and add it to result array.
* 2.2. Push 'right child' of popped item to stack.
* 2.3. Push 'left child' of popped item to stack.
*/
if (root == null) {
return [];
}
const stack = [];
const result = [];
stack.push(root);
while(stack.length > 0) {
let current = stack.pop();
result.push(current.val);
if (current.right) stack.push(current.right);
if (current.left) stack.push(current.left);
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment