目录
104.二叉树的最大深度
int maxDepth(struct TreeNode* root){
int depth_left,depth_right;
//结点为空时返回0
if(!root) return 0;
//左子树最大深度
depth_left=maxDepth(root->left);
//右子树最大深度
depth_right=maxDepth(root->right);
//最大深度=max(左子树深度,右子树深度)+1
return fmax(depth_left,depth_right)+1;
}
559.n叉树的最大深度
int maxDepth(struct Node* root) {
if(!root) return 0;
int dep=0;
//各子树最大深度的最大值最终覆盖到dep
for(int i=0;i<root->numChildren;i++){
dep=famx(dep,maxDepth(root->children[i]));
}
return dep+1;
}
111.二叉树的最小深度
题目链接:力扣
题目描述:
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
和104.二叉树的最大深度不同的是,最小深度的结点左右结点均为空。下面示例最小深度不为1:
int minDepth(struct TreeNode *root) {
int depth_left,depth_right;
//结点为空时返回0
if(!root) return 0;
//左子树最小深度
depth_left=minDepth(root->left);
//右子树最小深度
depth_right=minDepth(root->right);
//当一个左子树为空右不为空,最低点为右子树最小深度+1
if (root->left==NULL&&root->right!=NULL){
return 1+depth_right;
}
//当一个右子树为空左不为空,最低点为左子树最小深度+1
if (root->left!=NULL&&root->right==NULL) {
return 1+depth_left;
}
return fmin(depth_left,depth_right)+1;
}
222.完全二叉树的节点个数
题目链接:力扣
就这样就这样!完全二叉树也是二叉树
int countNodes(struct TreeNode* root){
//空树返回0
if(root==NULL) return 0;
else{
//左子树结点数+右子树节点数+1
return countNodes(root->left)+countNodes(root->right)+1;
}
}