Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Example 2:
[0, 105]
.-1000 <= Node.val <= 1000
/**
* 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 minDepth = function(root) {
let answer = 50000;
const queue = [[root, 1]];
if (!root) {
return 0;
}
while (queue.length) {
const [node, depth] = queue.shift();
if (depth >= answer) continue;
if (!node.left && !node.right) answer = depth;
if (node.left) queue.push([node.left, depth + 1]);
if (node.right) queue.push([node.right, depth + 1]);
}
return answer;
};
Given a binary tree root
, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Example 2:
[1, 10^5]
.[-10^4, 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 goodNodes = function(root) {
let answer = 0;
const queue = [[root, root.val]];
if (!root) {
return 0;
}
while (queue.length) {
let [node, maxValue] = queue.shift();
if (node.val >= maxValue) {
answer++;
maxValue = node.val;
}
if (node.left) queue.push([node.left, maxValue]);
if (node.right) queue.push([node.right, maxValue]);
}
return answer;
};
Given the root
of a binary tree, find the maximum value v
for which there exist different nodes a
and b
where v = |a.val - b.val|
and a
is an ancestor of b
.
A node a
is an ancestor of b
if either: any child of a
is equal to b
or any child of a
is an ancestor of b
.
[2, 5000]
.0 <= Node.val <= 10^5
/**
* 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 maxAncestorDiff = function(root) {
let diff = 0;
let minValue = 100000;
let maxValue = 0;
const dfs = (node, minValue, maxValue) => {
minValue = node.val < minValue ? node.val : minValue;
maxValue = node.val > maxValue ? node.val : maxValue;
if (!node.left && !node.right) {
diff = Math.max(diff, maxValue - minValue);
return;
}
if (node.left) dfs(node.left, minValue, maxValue);
if (node.right) dfs(node.right, minValue, maxValue);
}
dfs(root, minValue, maxValue);
return diff;
};