559. N 叉树的最大深度
559. N 叉树的最大深度
var maxDepth = function(root) {
if (!root) return 0;
let maxChild = 0;
const children = root.children;
for(const child of children) {
const childDepth = maxDepth(child);
maxChild = Math.max(maxChild, childDepth);
}
return maxChild + 1;
};
589. N 叉树的前序遍历
589. N 叉树的前序遍历
var preorder = function(root) {
let arr = [];
if (!root) return [];
function dfs(node) {
if (!node) return;
arr.push(node.val);
for (const child of node.children) {
dfs(child);
}
}
dfs(root);
return arr;
};
590. N 叉树的后序遍历
590. N 叉树的后序遍历
var postorder = function(root) {
let arr = [];
if (!root) return [];
function dfs(node) {
if (!node) return;
for (const child of node.children) {
dfs(child);
}
arr.push(node.val);
}
dfs(root);
return arr;
};
733. 图像渲染
733. 图像渲染
const floodFill = (image, sr, sc, newColor) => {
const m = image.length;
const n = image[0].length;
const oldColor = image[sr][sc];
if (oldColor == newColor) return image;
const fill = (i, j) => {
if (i < 0 || i >= m || j < 0 || j >= n || image[i][j] != oldColor) {
return;
}
image[i][j] = newColor;
fill(i - 1, j);
fill(i + 1, j);
fill(i, j - 1);
fill(i, j + 1);
};
fill(sr, sc);
return image;
};
LCP 07. 传递信息
LCP 07. 传递信息
var numWays = function(n, relation, k) {
let ways = 0;
const edges = new Array(n).fill(0).map(() => new Array());
for (const [src, dst] of relation) {
edges[src].push(dst);
}
const dfs = (index, steps) => {
if (steps === k) {
if (index === n - 1) {
ways++;
}
return;
}
const list = edges[index];
for (const nextIndex of list) {
dfs(nextIndex, steps + 1);
}
}
dfs(0, 0);
return ways;
}
513. 找树左下角的值
513. 找树左下角的值
var findBottomLeftValue = function(root) {
if (root == null) return null;
let queue = [];
queue.push(root);
let resNode = null;
while (queue.length) {
let len = queue.length;
for (let index = 0; index < len; index++) {
let node = queue.shift();
if (index === 0) resNode = node.val;
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}
return resNode;
};