1. 递归解法
解题思路:
递归到叶子结点才能计算树的深度。如果左子树为空,那么右子树的最小深度 + 1即为所求当前节点的最小深度;反之,右子树为空,那么左子树的最小深度即为所求当前节点的最小深度;如果均不为空,那么左右子树的最小深度+1即为当前节点的最小深度;
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. 迭代解法
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
int minDepth = 0;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
minDepth++;
for(int i = que.size(); i > 0; i--){
TreeNode *p = que.front();
que.pop();
if(!p->left && !p->right) return minDepth;
if(p->left) que.push(p->left);
if(p->right) que.push(p->right);
}
}
return minDepth;
}
};