Given the root
of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1
and 2h
nodes inclusive at the last level h
.
Design an algorithm that runs in less than O(n)
time complexity.
[0, 5 * 10^4]
.0 <= Node.val <= 5 * 10^4
/**
* 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}
*/
var countNodes = function(root) {
if (!root) return 0;
let count = 1;
count += countNodes(root.left);
count += countNodes(root.right);
return count;
};
You are given two m x n
binary matrices grid1
and grid2
containing only 0
's (representing water) and 1
's (representing land). An island is a group of 1
's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2
is considered a sub-island if there is an island in grid1
that contains all the cells that make up this island in grid2
.
Return the number of islands in grid2
that are considered sub-islands.
m == grid1.length == grid2.length
n == grid1[i].length == grid2[i].length
1 <= m, n <= 500
grid1[i][j]
and grid2[i][j]
are either 0
or 1
./**
* @param {number[][]} grid1
* @param {number[][]} grid2
* @return {number}
*/
var countSubIslands = function(grid1, grid2) {
const M = grid2.length;
const N = grid2[0].length;
let count = 0;
let isSubIsland = true;
const dfs = (row, col) => {
if (row < 0 || row >= M || col < 0 || col >= N || grid2[row][col] === 0) {
return;
}
if (grid1[row][col] === 0) {
isSubIsland = false;
return;
}
grid1[row][col] = 0;
grid2[row][col] = 0;
dfs(row + 1, col);
dfs(row - 1, col);
dfs(row, col + 1);
dfs(row, col - 1);
};
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
isSubIsland = true;
if (grid2[i][j] === 1) {
dfs(i, j);
if (isSubIsland) {
count++;
}
}
}
}
return count;
};
Given a string s
, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Example 2:
1 <= s.length <= 1000
s
consists of lowercase English letters./**
* @param {string} s
* @return {number}
*/
var countSubstrings = function(s) {
let count = 0;
const countPalindrome = (str, start, end) => {
while (start >= 0 && end < str.length && str[start] === str[end]) {
start--;
end++;
count++;
}
};
for (let i = 0; i < s.length; i++) {
countPalindrome(s, i, i); // odd-length palindromes
countPalindrome(s, i, i+1); // even-length palindromes
}
return count;
};
dddd