- Related Questions & Answers
- Program to find largest sum of non-adjacent elements of a list in Python
- Python Program to Find the Sum of all Nodes in a Tree
- Program to find sum of non-adjacent elements in a circular 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
- 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 in C++
- Program to find maximum sum of two non-overlapping sublists in Python
- Maximum sum of non-leaf nodes among all levels of the given binary tree in C++
- Maximum sum of nodes in Binary tree such that no two are adjacent using Dynamic Programming in C++ program
- Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming In C++
- Program to find sum of all elements of a tree in Python
- Program to find longest path between two nodes of a tree in Python
- Program to find maximum length of non-sharing words in Python
- Program to find the largest sum of the path between two nodes in a binary tree in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(10) root.left.left = TreeNode(4) root.left.right = TreeNode(3)

17

Advertisements