104.二叉树的最大深度
class Solution {
public:
int maxDepth(TreeNode* root)
{
if(root==nullptr)
return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
559.n叉树的最大深度
111.二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root)
{
if(root==nullptr)
return 0;
if(!root->left&&!root->right)
return 1;
int m1=minDepth(root->left);
int m2=minDepth(root->right);
if(root->left==nullptr||root->right==nullptr)
return m1+m2+1;
return min(m1,m2)+1;
}
};
222.完全二叉树的节点个数
class Solution {
public:
int countNodes(TreeNode* root)
{
if(root==nullptr)
return 0;
return countNodes(root->left)+countNodes(root->right)+1;
}
};
class Solution {
public:
// 统计树的深度
int countLevels(TreeNode* root) {
int levels = 0;
while (root) {
root = root->left; levels += 1;
}
return levels;
}
int countNodes(TreeNode* root){
// 2. 利用完全二叉树性质简化遍历次数
if(root == nullptr) return 0;
int left_levels = countLevels(root->left);
int right_levels = countLevels(root->right);
// 左子树深度等于右子树深度, 则左子树是满二叉树
if(left_levels == right_levels){
return countNodes(root->right) + (1<<left_levels);
}else{
return countNodes(root->left) + (1<<right_levels);
}
}
};
作者:zuo-10
链接:https://leetcode.cn/problems/count-complete-tree-nodes/solution/c-san-chong-fang-fa-jie-jue-wan-quan-er-cha-shu-de/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。