Last active
June 3, 2018 23:55
-
-
Save imjul1an/eeb3ddfd03109b3c72e518a28fbd61bd to your computer and use it in GitHub Desktop.
Traversing In-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 } | |
} | |
}; | |
/** | |
* In-order BST Traversal (Root, Left, Right). Recursive solution. | |
* @param {TreeNode} root | |
* @param {number[]} acc | |
* @return {number[]} | |
*/ | |
var inorderTraversal = function(root, acc = []) { | |
if (!!root) { | |
if (root.left) inorderTraversal(root.left, acc); | |
acc.push(root.val); | |
if (root.right) inorderTraversal(root.right, acc); | |
} | |
return acc; | |
}; | |
/** | |
* In-order BST Traversal (Root, Left, Right). Iterative solution. | |
* @param {TreeNode} root | |
* @return {number[]} | |
*/ | |
var inorderTraversal = function(root) { | |
/** | |
* 1. Create an empty stack S. | |
* 2. Initialize current node as root | |
* 3. Push the current node to S and set current = current->left until current is NULL | |
* 4. If current is NULL and stack is not empty then | |
* 4.1. Pop the top item from stack. | |
* 4.2. Print the popped item, set current = popped_item->right | |
* 4.3. Go to step 3. | |
* 5. If current is NULL and stack is empty then we are done. | |
*/ | |
if (root == null) { | |
return []; | |
} | |
const stack = []; | |
const result = []; | |
let isDone = false; | |
let current = root; | |
while (!isDone) { | |
if (current) { | |
stack.push(current); | |
current = current.left; | |
} else { | |
if (stack.length) { | |
let currentPopped = stack.pop(); | |
result.push(currentPopped.val); | |
current = currentPopped.right; | |
} else { | |
isDone = true | |
} | |
} | |
} | |
return result; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment