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:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7return its minimum depth = 2.
Runtime: 8 ms, faster than 97.02% of C++ online submissions for Minimum Depth of Binary Tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left != NULL && root->right == NULL) {
return minDepth(root->left) + 1;
}
if (root->left == NULL && root->right != NULL) {
return minDepth(root->right) + 1;
}
return min(minDepth(root->left) + 1, minDepth(root->right) + 1);
}
};
树的遍历计数问题,需要注意的是出现左右节点不同时存在时,需要取存在子节点的那个分支计数。
Runtime: 216 ms, faster than 99.76% of JavaScript online submissions for Minimum Depth of Binary Tree.
Memory Usage: 76.9 MB, less than 21.04% of JavaScript online submissions for Minimum Depth of Binary Tree.
/**
* 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 = 1;
const queue = [root];
let size;
while(queue.length > 0) {
size = queue.length;
for (let i = 0; i < size; i++) {
node = queue.shift();
if (!node.left && !node.right) {
return depth;
}
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
depth++;
}
return depth;
};