首页 > 其他 > 详细

LeetCode-层数最深叶子结点的和

时间:2020-02-22 20:36:30      阅读:62      评论:0      收藏:0      [点我收藏+]

层数最深叶子结点的和

LeetCode-1302

  • 这里可以采用上一题中求解二叉树的深度的方法。
  • 因为需要记录最深结点的值的和,所以这里可以边求和,如果遇到不符合最深结点时再将和sum=0.
/**
 * 给你一棵二叉树,请你返回层数最深的叶子节点的和。
 **/
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
      1
     /     2  3
   / \    4  5  6
 /       7        8
**/
class Solution {
private:
    int maxdepth=0;//树的最大深度
    int sum=0;//树的最大深度的结点值的和。
public:
    void DFS(TreeNode* node,int depth){
        if(!node->left&&!node->right){
            if(depth>maxdepth){
                sum=node->val;
                maxdepth=depth;
            }else if(depth==maxdepth){
                sum+=node->val;
            }
            return;
        }
        if(node->left){
            DFS(node->left,depth+1);
        }
        if(node->right){
            DFS(node->right,depth+1);
        }
    }
    int deepestLeavesSum(TreeNode* root) {
        if(root){
            DFS(root,1);
        }
        return sum;
    }
};

LeetCode-层数最深叶子结点的和

原文:https://www.cnblogs.com/GarrettWale/p/12346968.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!