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