
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to 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
- Related Articles
- Python Program to Find the Sum of all Nodes in a Tree
- Program to find largest sum of non-adjacent elements of a list in Python
- Program to find leaf and non-leaf nodes of a binary tree in Python
- Python Program to Find the Sum of All Nodes in a Binary Tree
- Program to find sum of non-adjacent elements in a circular list in python
- Maximum sum of nodes in Binary tree such that no two are adjacent in C++
- Maximum sum of nodes in Binary tree such that no two are adjacent using Dynamic Programming in C++ program
- Python Program to Count Number of Non Leaf Nodes of a given Tree
- Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming In C++
- Maximum sum of non-leaf nodes among all levels of the given binary tree in C++
- Program to find maximum sum of two non-overlapping sublists in Python
- Program to find the largest sum of the path between two nodes in a binary tree in Python
- Program to find longest path between two nodes of a tree in Python
- Program to find sum of all elements of a tree in Python
- Program to find the maximum width of a binary tree in Python

Advertisements