码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1302. Deepest Leaves Sum

时间:2019-12-29 10:38:07      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:pes   ==   col   root   node   +=   eve   leaves   evel   

题目如下:

Given a binary tree, return the sum of values of its deepest leaves.

Example 1:

技术图片

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

解题思路:我的方法是做两次遍历,第一次求树的最大深度,第二次求和。

代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    level = 0
    leavesSum = 0
    def getMaxLevel(self,node,level):
        self.level = max(self.level,level)
        if node == None:
            return
        if node.left != None:
            self.getMaxLevel(node.left,level + 1)
        if node.right != None:
            self.getMaxLevel(node.right,level + 1)
    def calc(self,node,level):
        if level == self.level:
            self.leavesSum += node.val
        if node == None:
            return
        if node.left != None:
            self.calc(node.left,level + 1)
        if node.right != None:
            self.calc(node.right,level + 1)


    def deepestLeavesSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.leavesSum = 0
        self.level = 0
        self.getMaxLevel(root,0)
        self.calc(root,0)
        return self.leavesSum
        

 

【leetcode】1302. Deepest Leaves Sum

标签:pes   ==   col   root   node   +=   eve   leaves   evel   

原文地址:https://www.cnblogs.com/seyjs/p/12114162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!