-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathbinary-tree-level-sum.py
More file actions
35 lines (33 loc) · 1001 Bytes
/
binary-tree-level-sum.py
File metadata and controls
35 lines (33 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@param level: the depth of the target level
@return: An integer
"""
def levelSum(self, root, level):
# write your code here
ret = 0
if root and (level > 0):
ilevel = 1
curr_nodes = [root]
next_nodes = []
while ilevel < level:
for node in curr_nodes:
if node.left:
next_nodes.append(node.left)
if node.right:
next_nodes.append(node.right)
ilevel += 1
curr_nodes = next_nodes
next_nodes = []
for node in curr_nodes:
ret += node.val
return ret
# easy: https://www.lintcode.com/problem/binary-tree-level-sum/