主题
二叉树的最小深度
javascript
let root = {
val: "1",
left: {
val: "2",
left: null,
right: null,
},
right: {
val: "5",
left: {
val: "6",
left: null,
right: null,
},
right: {
val: "7",
left: null,
right: null,
},
},
};第一种
javascript
var minDepth = function (root) {
if (root == null) return 0;
if (root.left == null && root.right == null) return 1;
//常量表示在 JavaScript 中最大的安全整数
let nums = Number.MAX_SAFE_INTEGER;
if (root.left != null) {
nums = Math.min(minDepth(root.left), nums);
}
if (root.right != null) {
nums = Math.min(minDepth(root.right), nums);
}
return nums + 1;
};第二种
javascript
var minDepth = function (root) {
if (!root) return 0;
let stack = [[root, 1]];
console.log(stack.length);
while (stack.length) {
let [o, n] = stack.shift();
if (!o.left && !o.right) {
return n;
}
if (o.left) stack.push([o.left, n + 1]);
if (o.right) stack.push([o.right, n + 1]);
}
};javascript
console.log(minDepth(root));