diff --git a/sik9252/BalancedBinaryTree.js b/sik9252/BalancedBinaryTree.js new file mode 100644 index 0000000..f5c48c6 --- /dev/null +++ b/sik9252/BalancedBinaryTree.js @@ -0,0 +1,19 @@ +var isBalanced = function (root) { + function getHeight(node) { + if (node === null) return 0; + return Math.max(getHeight(node.left), getHeight(node.right)) + 1; + } + + function check(node) { + if (node === null) return true; + + const leftH = getHeight(node.left); + const rightH = getHeight(node.right); + + if (Math.abs(leftH - rightH) > 1) return false; + + return check(node.left) && check(node.right); + } + + return check(root); +}; diff --git a/sik9252/ImplementQueueUsingStacks.js b/sik9252/ImplementQueueUsingStacks.js new file mode 100644 index 0000000..9e40280 --- /dev/null +++ b/sik9252/ImplementQueueUsingStacks.js @@ -0,0 +1,57 @@ +var MyQueue = function () { + this.stack = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MyQueue.prototype.push = function (x) { + this.stack.push(x); +}; + +/** + * @return {number} + */ +MyQueue.prototype.pop = function () { + if (this.stack.length === 1) { + return this.stack.pop(); + } + + const top = this.stack.pop(); + const result = this.pop(); + this.stack.push(top); + + return result; +}; + +/** + * @return {number} + */ +MyQueue.prototype.peek = function () { + if (this.stack.length === 1) { + return this.stack[this.stack.length - 1]; + } + + const top = this.stack.pop(); + const result = this.peek(); + this.stack.push(top); + + return result; +}; + +/** + * @return {boolean} + */ +MyQueue.prototype.empty = function () { + return this.stack.length === 0; +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * var obj = new MyQueue() + * obj.push(x) + * var param_2 = obj.pop() + * var param_3 = obj.peek() + * var param_4 = obj.empty() + */ diff --git a/sik9252/LinkedListCycle.js b/sik9252/LinkedListCycle.js new file mode 100644 index 0000000..1055f92 --- /dev/null +++ b/sik9252/LinkedListCycle.js @@ -0,0 +1,15 @@ +var hasCycle = function (head) { + const visited = new Set(); + let cur = head; + + while (cur !== null) { + if (visited.has(cur)) { + return true; + } + + visited.add(cur); + cur = cur.next; + } + + return false; +}; diff --git a/sik9252/LowestCommonAncestorOfBinarySearchTree.js b/sik9252/LowestCommonAncestorOfBinarySearchTree.js new file mode 100644 index 0000000..73fba13 --- /dev/null +++ b/sik9252/LowestCommonAncestorOfBinarySearchTree.js @@ -0,0 +1,17 @@ +var lowestCommonAncestor = function (root, p, q) { + let cur = root; + const low = Math.min(p.val, q.val); + const high = Math.max(p.val, q.val); + + while (cur !== null) { + if (high < cur.val) { + cur = cur.left; + } else if (low > cur.val) { + cur = cur.right; + } else { + return cur; + } + } + + return null; +};