题⽬中说的是:最⼩深度是从根节点到最近叶⼦节点的最短路径上的节点数量。注意是叶⼦节点。
什么是叶⼦节点,左右孩⼦都为空的节点才是叶⼦节点!
递归法
1、确定递归的参数和返回值:
参数为要传入的二叉树的根节点,返回的是int 型的深度。
int getDepth(TreeNode* node)
2、确定终止条件
if(node==nullptr) return 0;
3、确定单层递归的逻辑
错误代码
int leftmindepth=getDepth(node->left);
int rightmindepth=getDepth(node->right);
int mindepth=min(leftdepth,rightdepth);
return 1+depth;
犯了一个错误,请看下图
如果这么求的话,没有左孩⼦的分⽀会算为最短深度。
所以,如果左⼦树为空,右⼦树不为空,说明最⼩深度是1 +右⼦树的深度。
反之,右⼦树为空,左⼦树不为空,最⼩深度是1 +左⼦树的深度。最后如果左右⼦树都不为空,返回左右⼦树深度最⼩值+ 1。
正确的代码:
int leftmindepth=getDepth(node->left);
int rightmindepth=getDepth(node->right);
//当一个左子树为空,右子树不为空,这时并不是最低点。
if(node->left==nullptr && node->right!=nullptr)
{
int mindepth=rightmindepth;
return 1+mindepth;
}
if(node->right==nullptr && node->left!=nullptr)
{
int mindepth=leftmindepth;
return 1+mindepth;
}
int mindepth=min(leftmindepth,rightmindepth);
return 1+mindepth;
遍历的顺序为后序(左右中),可以看出:求⼆叉树的最⼩深度和求⼆叉树的最⼤深度的差别主要在于处理左右孩⼦不为空的逻辑。
完整递归代码:
class Solution {
public:
int getDepth(TreeNode* node)
{
if(node==nullptr) return 0;
int leftmindepth=getDepth(node->left);
int rightmindepth=getDepth(node->right);
//当一个左子树为空,右子树不为空,这时最低点是右子树的深度+1。
if(node->left==nullptr && node->right!=nullptr){
return 1+ rightmindepth;
}
//当⼀个右⼦树为空,左子树不为空,这时最低点是左子树的深度+1。
if(node->right==nullptr && node->left!=nullptr){
return 1+leftmindepth;
}
return 1+min(leftmindepth,rightmindepth);
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
迭代法
class Solution{
public:
int minDepth(TreeNode* root) {
if(root==nullptr) return 0;
queue<TreeNode*> que;
que.push(root);
int depth=0;
while(!que.empty()) {
int size=que.size();
depth++;
for(int ii=0;ii<size;ii++) {
TreeNode* node=que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
if(node->left==nullptr&&node->right==nullptr) return depth;
}
}
return depth;
}
};
注意,只有当左右孩⼦都为空的时候,才说明遍历到最低点了,退出。