【题目】111. 二叉树的最小深度
【题目考察】:二叉树
【目标复杂度】: O(n)
【解法一】:递归法
/**
* 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) {
if (!root) {
return 0;
}
const leftDepth = minDepth(root.left);
const rightDepth = minDepth(root.right);
if (!root.left && root.right) {
return 1 + rightDepth;
}
if (!root.right && root.left) {
return 1 + leftDepth;
}
return 1 + Math.min(leftDepth, rightDepth);
};
【解法二】:迭代法
/**
* 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) {
if (!root) return 0;
let depth = 0;
const queue = [root];
while(queue.length) {
const size = queue.length;
depth++;
for(let i = 0; i < size; i++) {
const front = queue.shift();
if (front.left) queue.push(front.left);
if (front.right) queue.push(front.right);
if (!front.left && !front.right) {
return depth;
}
}
}
return depth;
};