111. Minimum Depth of Binary Tree
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 7
return its minimum depth = 2.
题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
法一:DFS递归
递归思想的练习。非递归不写了。
相比求最大深度的题,本题多了一个小陷阱:深度代表的是从根节点出发到叶子节点结束。
特殊:[3,null,20,15,7],答案是3二不是1。
因此向上返回长度时,需要判断当前节点是否左右都有孩子,有则返回左右中较小深度,无则返回较大深度(较小值其实就是0)。
/**
* 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;
int l = minDepth(root->left);
int r = minDepth(root->right);
if(root->left && root->right) return min(l,r)+1;
else return max(l,r)+1;
}
};
法二:BFS
一个小坑:左右只有一边有孩子时,以有孩子的那边的深度为准,所以要从是否叶子节点的角度出发。
例如:[3,null,20,15,7]答案为3 不为1,[1,2,3,4,null,null,5]答案为3 不为2。
/**
* 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) return 0;
queue<TreeNode*> q;
q.push(root);
int dep = 1;
while(!q.empty()){
int len = q.size();
for(int i=0; i<len; ++i){
auto node = q.front();
q.pop();
if(!node->left && !node->right){
return dep;
}
if(node->left)q.push(node->left);
if(node->right)q.push(node->right);
}
++dep;
}
return dep;
}
};