Skip to main content

4 posts tagged with "stack"

View All Tags

· One min read

https://leetcode.com/problems/binary-tree-preorder-traversal/

Solution 1

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function (root) {
let result = [];

traversalHelper(root, result);

return result;
};

const traversalHelper = (root, result) => {
if (root === null) {
return;
}
result.push(root.val);
traversalHelper(root.left, result);
traversalHelper(root.right, result);
};

· One min read

https://leetcode.com/problems/binary-tree-postorder-traversal/

Solution 1

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
let result = [];
traversalHelper(root, result);
return result;
};

const traversalHelper = (root, result) => {
if (root === null) {
return;
}
result.unshift(root.val);
traversalHelper(root.right, result);
traversalHelper(root.left, result);
};

· One min read

https://leetcode.com/problems/valid-parentheses/

Solution 1

/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
if (s.length % 2 !== 0) {
return false;
}

const stack = [];
const brackets = {
'(': ')',
'{': '}',
'[': ']',
};

for (let i = 0; i < s.length; i++) {
if (Object.keys(brackets).includes(s[i])) {
stack.push(s[i]);
} else {
if (brackets[stack[stack.length - 1]] === s[i]) {
stack.pop();
} else {
return false;
}
}
}
return stack.length === 0;
};

Runtime: 240 ms

Memory Usage: 51.4 MB

· One min read

https://leetcode.com/problems/binary-tree-inorder-traversal/

Solution 1

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
let stack = [];
let result = [];

while (root !== null || stack.length !== 0) {
while (root !== null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
result.push(root.val);
root = root.right;
}
return result;
};