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

层数最深叶子结点的和

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;
    }
};
posted @ 2020-02-22 20:21  Garrett_Wale  阅读(408)  评论(0)    收藏  举报