【无标题】1302 层数最深叶子节点的和

今天还挺难过,学了这么久的树,递归的题还是有问题,我什么时候才能明白呀,有时候感觉自己不适合学习,不适合学计算机。

复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
  //先定义最大深度
  int max1;
  void depthmax(TreeNode* root,int dep){
    if(root==NULL){
        return ;
    }
    if(dep>max1){
        max1=dep;
    }
    if(root->left!=NULL){
    depthmax(root->left,dep+1);
    }
    if(root->right!=NULL){
    depthmax(root->right,dep+1);
    }
  }

  int sumdepthmax(TreeNode *root,int dep){
    if(root==NULL){
        return 0;
    }
    if(dep==max1){
    return root->val;
    }
    int suml=sumdepthmax(root->left,dep+1);
    int sumr=sumdepthmax(root->right,dep+1);
    return suml+sumr;
  }
public:
    int deepestLeavesSum(TreeNode* root) {
    max1=0;
    depthmax(root,0);
    return sumdepthmax(root,0);
    }
};

这个题首先要两个函数,一个函数来求最大深度,我做第二遍的时候感觉思路很模糊,就是因为我没有想到先定义一个最大深度,然后再不断更新最大深度的值,如果左子树的深度大于最大深度,我们就将最大深度的值替换,右子树也一样。

第二个函数是求和函数,首先我的递归出口的条件错了,我的判断是假如左子树和右子树均为空的时候,这样反而会漏了最大深度,因为这样做相当于只要是没有孩子节点,就返回0,而我们要的是最大深度的节点,正确的应该是当此节点为空的时候,我们返回0,

相关推荐
计算机学姐2 小时前
基于SpringBoot的宠物诊所管理系统
java·vue.js·spring boot·后端·spring·elementui·宠物
isxhyeah2 小时前
python 数据结构 排序算法
数据结构·python·排序算法
invincible_Tang2 小时前
AcWing 796. 子矩阵的和 _
数据结构·算法
悟能不能悟2 小时前
idea默认的快捷键和eclipse配置快捷键对比,列出一些常用的
java·eclipse·intellij-idea
米粒12 小时前
力扣算法刷题 Day 8
算法·leetcode·职场和发展
晨晖22 小时前
java容器类的博客
java·开发语言
bug攻城狮2 小时前
Spring Boot项目启动时输出PID、CPU和内存信息的4种方法
java·spring boot·后端·logback
MegaDataFlowers2 小时前
Maven
java·maven
Sakinol#2 小时前
Leetcode Hot 100 —— 普通数组
算法·leetcode