代码随想录刷题-Day16-二叉树
leetcode-104.二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
错误解法:
void travelsal(struct TreeNode *cur, int *left_n, int *right_n){
if(cur==NULL|| left_n==NULL)
return;
travelsal(cur->left, left_n, right_n);
if(cur->left!=NULL){
(*left_n)++;
}
travelsal(cur->right, left_n, right_n);
if(cur->right!=NULL){
(*right_n)++;
}
}
int maxDepth(struct TreeNode* root){
if(root==NULL){
return 0;
}
int *left_n=(int *)malloc(sizeof(int));
*left_n=0;
int *right_n=(int *)malloc(sizeof(int));
*right_n=0;
travelsal(root, left_n, right_n);
if(left_n==NULL||right_n==NULL){
return -1;
}
//printf("left=%d,right=%d",*left_n,*right_n);
return *left_n > *right_n ? (*left_n +1 ) : (*right_n +1);
}
将计算深度的方法放在外面导致多算
放在递归内部的方法:
leetcode-111.二叉树的最小深度
1、递归的输入/输出:节点/较小的那个深度
2、终止条件:节点为空,深度为0;子节点都为空,深度为1
3、每层处理的问题:
int minDepth(struct TreeNode* root){
if(root==NULL)
return 0;
int depth_min=INT_MAX;
/*return fmin( minDepth(root->left)==0 ? 9999 : (minDepth(root->left)), minDepth(root->right)==0 ? 9999 : (minDepth(root->right)) )+1;
*/
if(root->left==NULL && root->right==NULL){
return 1;
}
if(root->left!=NULL){
depth_min=fmin(minDepth(root->left), depth_min);
//printf("depth_left=%d\n",depth_min);
}
if(root->right!=NULL){
depth_min=fmin(minDepth(root->right), depth_min);
//printf("depth_lrigtt=%d\n",depth_min);
}
return depth_min+1;
}
leetcode-222.完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树
的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第
h 层,则该层包含 1~ 2h 个节点。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-complete-tree-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归,同前序遍历
void travel(struct TreeNode *root, int *count){
if(root==NULL || count == NULL)
return ;
(*count)+=1;
//printf("%d,val=%d\n",*count,root->val);
travel(root->left, count);
travel(root->right, count);
}
int countNodes(struct TreeNode* root){
if(root==NULL)
return 0;
int *count=(int *)malloc(sizeof(int));
*count=0;
travel(root, count);
if(count==NULL){
return -1;
}
return *count;
}