A power of 326. 3

// var isPowerOfThree = function(n) {
// let b = 1
// while (b < n) {
// b = 3 * b
/ /}
// return b == n ? true : false
// };

var isPowerOfThree = function(n) {
    return n > 0 && 1162261467 % n === 0;
};
Copy the code

200. Number of islands

Through the experiment, it is found that there is no need to add array to judge whether to traverse, which increases the space complexity. We can directly traverse the original array and set 1 to 0

function helper(grid, i, j, rows, cols) {
  if (i < 0 || j < 0 || i > rows - 1 || j > cols - 1 || grid[i][j] === "0")
    return;

  grid[i][j] = "0";

  helper(grid, i + 1, j, rows, cols);
  helper(grid, i, j + 1, rows, cols);
  helper(grid, i - 1, j, rows, cols);
  helper(grid, i, j - 1, rows, cols);
}

var numIslands = function(grid) {
  let res = 0;
  const rows = grid.length;
  if (rows === 0) return 0;
  const cols = grid[0].length;
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (grid[i][j] === "1") { helper(grid, i, j, rows, cols); res++; }}}return res;
};
Copy the code

230. The KTH smallest element in a binary search tree

Middle order traversal sort

var kthSmallest = function(root, k) {
    let i = 0;
    let val = null;
    travel(root);
    return val;

    function travel(node) {
        node.left && travel(node.left);

        if (++i === k) {
            val = node.val;
            return; } node.right && travel(node.right); }};Copy the code