21. 合并两个有序链表
/*** Definition for singly-linked list.* function ListNode(val, next) {* this.val = (val===undefined ? 0 : val)* this.next = (next===undefined ? null : next)* }*//*** @param {ListNode} list1* @param {ListNode} list2* @return {ListNode}*/var mergeTwoLists = function(list1, list2) {if (list1 === null) {return list2} else if (list2 === null) {return list1} else if (list1.val < list2.val) {var next = list1.nextlist1.next = mergeTwoLists(list2, next)return list1} else {// 为什么这里else if就挂了var next = list2.nextlist2.next = mergeTwoLists(list1, next)return list2}};
509. 斐波那契数
/*** @param {number} n* @return {number}*/var fib = function(n) {if (n <= 1) {return n}return fib(n - 1) + fib(n - 2)};
94. 二叉树的中序遍历
1、dfs
/*** 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[]}*/// 1、dfs很简单//2、用迭代var inorderTraversal = function(root) {var res = []var dfs = (root) => {if (!root) {return}dfs(root.left)res.push(root.val)dfs(root.right)}dfs(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[]}*/// 1、dfs很简单//2、用迭代var inorderTraversal = function(root) {var res = []var stack = []while(stack.length || root) {while(root) {stack.push(root)root = root.left}// 左中右root = stack.pop()res.push(root.val)root = root.right}return res};
429. N叉树的层序遍历
/*** // Definition for a Node.* function Node(val,children) {* this.val = val;* this.children = children;* };*//*** @param {Node|null} root* @return {number[][]}*/var levelOrder = function(root) {let q = [root]let res = []if (!root) {return [];}while(q.length) {let len = q.lengthlet level = []for (let j = 0; j < len; ++j) {let tmp = q.shift()for (const child of tmp.children) {q.push(child);}level.push(tmp.val)}res.push(level)}return res};
48. 旋转图像
// 对于矩阵中第 ii 行的第 jj 个元素,在旋转后,它出现在倒数第 ii 列的第 jj 个位置。var rotate = function(matrix) {const n = matrix.length;const matrix_new = new Array(n).fill(0).map(() => new Array(n).fill(0));for (let i = 0; i < n; i++) {for (let j = 0; j < n; j++) {matrix_new[j][n - i - 1] = matrix[i][j];}}for (let i = 0; i < n; i++) {for (let j = 0; j < n; j++) {matrix[i][j] = matrix_new[i][j];}}};
