今日内容:
● 104.二叉树的最大深度 559.n叉树的最大深度
● 111.二叉树的最小深度
● 222.完全二叉树的节点个数
104.二叉树的最大深度
1.解题思路
最大深度,那么取左右儿子中的最大深度+自己的深度1;
2.代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left),maxDepth(root->right)) + 1;
}
};
111.二叉树的最小深度
1.解题思路
题目要读题理解。如果节点为空,那么深度为0; 当左右儿子都不为空,取小深度的那个儿子,如果有一方为空,那么取深度大的儿子
2.代码
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
if(root->left && root->right)
return min(minDepth(root->left),minDepth(root->right)) + 1;
else
return max(minDepth(root->left),minDepth(root->right)) + 1;
}
};
222.完全二叉树的节点个数
1.解题思路
对每个节点都可以看出一颗二叉树,如果节点为空,那么返回该节点数量为0,否则该节点1+左儿子数量+右儿子数量。
2.代码
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
else{
return countNodes(root->left) + countNodes(root->right) + 1;
}
}
};
总结
我理解的是对每个节点就把他当成一颗子树去理解,因为树的子树还是一颗树可以找递归的条件。