Skip to content

Commit 5deef98

Browse files
Add function to calculate max sum of non-adjacent nodes
Implement a solution to maximize sum of non-adjacent nodes in a binary tree.
1 parent b6400fa commit 5deef98

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

October_2025/potd_13_10_2025.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/* Given the root of a binary tree with integer values. Your task is to select a subset of nodes such that the sum of their values is maximized, with the condition that no two selected nodes are directly connected that is, if a node is included in the subset, neither its parent nor its children can be included. */
2+
3+
class potd_13_10_2025:
4+
def getMaxSum(self, root):
5+
def solve(node):
6+
if not node:
7+
return (0, 0) # (include, exclude)
8+
9+
left_include, left_exclude = solve(node.left)
10+
right_include, right_exclude = solve(node.right)
11+
12+
# If we include this node
13+
include = node.data + left_exclude + right_exclude
14+
15+
# If we exclude this node
16+
exclude = max(left_include, left_exclude) + max(right_include, right_exclude)
17+
18+
return (include, exclude)
19+
20+
include, exclude = solve(root)
21+
return max(include, exclude)

0 commit comments

Comments
 (0)