题目描述
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.
解法
- 递归方式:很容易理解,直接上代码
class Solution {
public:
int run(TreeNode *root) {
if(!root) return 0;
if(!root -> left) return 1 + run(root -> right);
if(!root -> right) return 1 + run(root -> left);
return 1 + min(run(root -> left), run(root -> right));
}
};
- 非递归方式:基于队列对二叉树做层序遍历,用一个整型变量记录层数。层序遍历遇到的第一个叶节点即是“最浅”的叶节点,此时返回层数
class Solution {
public:
int run(TreeNode *root) {
if(!root) return 0;
queue<TreeNode*> q;
q.push(root);
int res = 0; // 记录层数
while(!q.empty()) {
++res;
for(int i = q.size(); i > 0; --i) { // 遍历第res层,把res+1层的节点添加到队列
auto p = q.front();
q.pop();
if(!p -> left && !p -> right) // 遇到第一个叶节点即返回层数
return res;
if(p -> left)
q.push(p -> left);
if(p -> right)
q.push(p -> right);
}
}
return res;
}
};