
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Sum of Non-Adjacent Nodes of a Tree in Python
Suppose we have a binary tree, we have to find the maximum sum of the values that can be obtained given no two values can be adjacent parent to child.
So, if the input is like
then the output will be 17 as 10, 4, 3 are not adjacent to each other.
To solve this, we will follow these steps −
- Define a function f() . This will take node
- if node is null, then
- return (0, 0)
- (a, b) := f(left of node)
- (c, d) := f(right of node)
- return a pair (maximum of value of node + b + d and a + c, a + c)
- from the main method call f(root) and return the first value of it
Let us see the following implementation to get better understanding −
Example
class TreeNode: def __init__(self, data, left = None, right = None): self.val = data self.left = left self.right = right def f(node): if not node: return 0, 0 a, b = f(node.left) c, d = f(node.right) return max(node.val + b + d, a + c), a + c class Solution: def solve(self, root): return f(root)[0] ob = Solution() root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(10) root.left.left = TreeNode(4) root.left.right = TreeNode(3) print(ob.solve(root))
Input
root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(10) root.left.left = TreeNode(4) root.left.right = TreeNode(3)
Output
17
Advertisements