Skip to content

Instantly share code, notes, and snippets.

@voischev
Last active April 21, 2016 10:36
Show Gist options
  • Save voischev/835cf4bce891f5cb593dce2135ce7b31 to your computer and use it in GitHub Desktop.
Save voischev/835cf4bce891f5cb593dce2135ce7b31 to your computer and use it in GitHub Desktop.
javascript-stack-tree
var tree = [
{
val: 1,
next: [
{val: 2, next: null},
{val: 3, next: [{val: 4, next: null}]}
]
}
];
var stack = [tree];
while(stack.length) {
var subTree = stack.pop();
for (var i = 0; i < subTree.length; i++) {
var sub = subTree[i];
sub.next && stack.push(sub.next);
console.log(sub.val);
}
}
////
var s = '(({}[][])[]){}';
var i = 1;
var stack = [];
stack.push(s[0]);
var isValid = function(s) {
while(s[i]) {
var cur = s[i];
var last = stack[stack.length - 1];
if(
(last === '(' && cur === ')') ||
(last === '{' && cur === '}') ||
(last === '[' && cur === ']')
) {
stack.pop();
} else {
stack.push(cur);
}
i++;
}
return stack.length === 0;
}
console.log(isValid(s));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment