104.二叉树的最大深度 (优先掌握递归)
什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。
大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。
题目链接/文章讲解/视频讲解: 代码随想录
111.二叉树的最小深度 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
特殊情况是一个子树为
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;
if(root->left == nullptr&&root->right != nullptr){
return minDepth(root->right)+1;
}
if(root->right == nullptr&&root->left != nullptr){
return minDepth(root->left)+1;
}
return min(minDepth(root->left),minDepth(root->right))+1;
}
};
222.完全二叉树的节点个数(优先掌握递归)
需要了解,普通二叉树 怎么求,完全二叉树又怎么求
题目链接/文章讲解/视频讲解:15代码随想录
完全二叉树的定义:
除去最后一行,以上level全满,最后一行左对齐 AC
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr) return 0;
if(root->left==nullptr&&root->right==nullptr) return 1;
int leftcount = countNodes(root->left);
int rightcount = countNodes(root->right);
if(leftcount>=rightcount){
return leftcount+rightcount+1;
}else{
return leftcount+rightcount;
}
}
};