Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9739e2c

Browse files
Max Level Sum in Binary Tree
1 parent e3c7b38 commit 9739e2c

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Problem Link: https://practice.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1/
3+
4+
Given a Binary Tree having positive and negative nodes.
5+
Find the maximum sum of a level in the given Binary Tree.
6+
7+
Example 1:
8+
Input :
9+
4
10+
/ \
11+
2 -5
12+
/ \ / \
13+
-1 3 -2 6
14+
Output: 6
15+
Explanation :
16+
Sum of all nodes of 0'th level is 4
17+
Sum of all nodes of 1'th level is -3
18+
Sum of all nodes of 2'th level is 6
19+
Hence maximum sum is 6
20+
21+
Example 2:
22+
Input :
23+
1
24+
/ \
25+
2 3
26+
/ \ \
27+
4 5 8
28+
/ \
29+
6 7
30+
Output : 17
31+
32+
Explanation: Maximum sum is at level 2.
33+
34+
Your Task:
35+
You dont need to read input or print anything. Complete the function
36+
maxLevelSum() which takes root node as input parameter and
37+
returns the maximum sum of any horizontal level in the given Binary Tree.
38+
39+
Expected Time Complexity: O(N)
40+
Expected Auxiliary Space: O(N)
41+
"""
42+
class Solution:
43+
def maxLevelSum(self, root):
44+
return max(self.helper(root))
45+
46+
def helper(self, root, level=0, levels_sum=None):
47+
if not root:
48+
return 0
49+
50+
if not levels_sum:
51+
levels_sum = []
52+
if level == len(levels_sum):
53+
levels_sum.append(0)
54+
55+
levels_sum[level] += root.data
56+
57+
self.helper(root.left, level+1, levels_sum)
58+
self.helper(root.right, level+1, levels_sum)
59+
return levels_sum

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /