Runtime: 8 ms, faster than 95.80% of C++ online submissions for Minimum Depth of Binary Tree.
Memory Usage: 19.5 MB, less than 90.48% of C++ online submissions for Minimum Depth of Binary Tree.
实际这里是从根节点到叶子节点层数的问题;
左右子树都为NULL回1,左(右)子树为NULL,返回右(左)子树深度+1,否则min(左,右)+1
深度优先,广度优先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//最小深度即到最近的叶子节点的距离,这里的重点是到叶子节点。因此若某一分支为NULL,则应该只考虑另一支。
// class Solution {
// public:
// int minDepth(TreeNode* root) {
// // if(root == NULL) return 0;
// // if(root->left == NULL && root->right == NULL)
// // return 1;
// // else if(root->left == NULL)
// // return minDepth(root->right)+1;
// // else if(root->right == NULL)
// // return minDepth(root->left)+1;
// // else{
// // return min(minDepth(root->left), minDepth(root->right))+1;
// // }
// if(root == NULL) return 0;
// // if(root->left == NULL && root->right == NULL)
// // return 1;
// else if(root->left == NULL)
// return minDepth(root->right)+1;//右边可能为NULL,也有可能不是
// else if(root->right == NULL)
// return minDepth(root->left)+1;
// else{
// return min(minDepth(root->left), minDepth(root->right))+1;
// }
// }
// };
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode*> q;
q.push(root);
TreeNode* last = q.back();
int depth = 0;
while(q.size()){//没有empty成员函数?
TreeNode* now = q.front();
q.pop();//pop不返回值
size_t siz = q.size();
if(now->left)//搞清楚有没有!
q.push(now->left);//是push,而不是push_back
if(now->right)
q.push(now->right);
if(siz == q.size()){//标志着这是叶子节点
return depth+1;//+1?
}
if(now == last){//该层搜索完成
depth++;
last = q.back();//最右面的必为新一层的最后一个
}
}
return -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 == NULL)
return 0;//这句很重要
if(root->left == NULL)//左边是空,左边就没有意义了,不能0+1
return minDepth(root->right)+1;
if(root->right == NULL)
return minDepth(root->left)+1;
int left = minDepth(root->left);
int right = minDepth(root->right);
return min(left, right) + 1;
}
};
空;左空;右空;都空