题目:
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:
Input: root = [3,9,20,null,null,15,7] Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6] Output: 5
Constraints:
- The number of nodes in the tree is in the range
[0, 105]
. -1000 <= Node.val <= 1000
思路1:
这是比较好的练手题,DFS和BFS都可以做,先讨论DFS。首先如果当前root为空,则这一层不算,返回0。如果只有左,则返回当前一层1+往左递归;如果只有右,返回当前一层1+往右递归;左右都有则返回当前一层1+左右中相对小的一种情况即可。优点是代码比较短,不用额外空间,只需要函数内递归栈即可,但是缺点显然是运行较慢,需要遍历所有可能情况。
代码1:
/**
* 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;
if(!root->left)
return 1 + minDepth(root->right);
if(!root->right)
return 1 + minDepth(root->left);
return 1+min(minDepth(root->left),minDepth(root->right));
}
};
思路2:
用队列模拟BFS。先检查初始root,为空直接返回0,否则记depth为1。之后就是常规的BFS,如果当前node是叶子节点,直接返回当前depth;否则如果有左就把左加入队列,有右就把右加入队列即可。最后返回depth。
代码2:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root)
return 0;
int depth=1;
queue<TreeNode*> q;
q.push(root);
while(q.size())
{
int len=q.size();
for(int i=0;i<len;i++)
{
auto t=q.front();
q.pop();
if(!t->left&&!t->right)
return depth;
if(t->left)
q.push(t->left);
if(t->right)
q.push(t->right);
}
depth++;
}
return depth;
}
};