leetcode1302 Deepest Leaves Sum

 1 """
 2 Given a binary tree, return the sum of values of its deepest leaves.
 3 Example 1:
 4 Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
 5 Output: 15
 6 """
 7 """
 8 层次遍历
 9 """
10 class TreeNode:
11     def __init__(self, x):
12         self.val = x
13         self.left = None
14         self.right = None
15 
16 class Solution:
17     def deepestLeavesSum(self, root):
18         if root == None:
19             return 0
20         queue = []
21         queue.append(root)
22         while queue:
23             res = 0
24             newqueue = []
25             n = len(queue)
26             for _ in range(n):
27                 x = queue.pop(0)
28                 res += x.val
29                 if x.left != None:
30                     newqueue.append(x.left)
31                 if x.right != None:
32                     newqueue.append(x.right)
33             queue = newqueue
34         return res

 

posted @ 2020-02-08 19:56  yawenw  阅读(148)  评论(0编辑  收藏  举报