/*** @param {number} capacity*/varLRUCache=function(capacity){this.capacity = capacity;this.map =newMap();};/** * @param {number} key* @return {number}*/LRUCache.prototype.get=function(key){if(this.map.has(key)){let value =this.map.get(key);this.map.delete(key);this.map.set(key, value);return value;}else{return-1;}};/** * @param {number} key * @param {number} value* @return {void}*/LRUCache.prototype.put=function(key, value){if(this.map.has(key)){let value =this.map.get(key);this.map.delete(key);}this.map.set(key, value);if(this.map.size >this.capacity){this.map.delete(this.map.keys().next().value);}};/*** Your LRUCache object will be instantiated and called as such:* var obj = new LRUCache(capacity)* var param_1 = obj.get(key)* obj.put(key,value)*/
44 二叉树的中序遍历
方法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[]}*/varinorderTraversal=function(root){var res =[];vartraversal=function(root){if(root ==null){return;}traversal(root.left);// 左res.push(root.val);// 根traversal(root.right);// 右}traversal(root);return res;};
方法2:迭代法。
遍历顺序与处理顺序不同。
/*** 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[]}*/varinorderTraversal=function(root){var res =[];// 存放结果var vis =[];// 模拟遍历队列,存放访问过的元素while(root !=null|| vis.length !=0){if(root !=null){vis.push(root);root = root.left;// 左}else{root = vis.pop();res.push(root.val);// 根root = root.right;// 右}}return res;};