Last active
June 3, 2018 19:08
-
-
Save imjul1an/d1ee138d99f08e2de67cd0be19fbe3db to your computer and use it in GitHub Desktop.
Traversing Pre-order BST
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
/* 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