Binary Tree Maximum Path Sum
Try to solve the Binary Tree Maximum Path Sum problem.
Statement
Given the root of a binary tree, return the maximum sum of any non-empty path.
A path in a binary tree is defined as follows:
- A sequence of nodes in which each pair of adjacent nodes must have an edge connecting them.
- A node can only be included in a path once at most.
- Including the root in the path is not compulsory.
You can calculate the path sum by adding up all node values in the path. To solve this problem, calculate the maximum path sum given the root of a binary tree so that there won’t be any greater path than it in the tree.
Constraints:
- Number of nodes in the tree .
-
Node.value
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Binary Tree Maximum Path Sum
What is the maximum path sum for the given binary tree?
-8
/ \
2 17
/ \ / \
1 4 24 5
level order = [-8, 2, 17, 1, 4, 24, 5]
45
46
47
48
Figure it out!
Here’s a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in main.py
in the following coding playground.
# Definition of a binary tree node# class TreeNode:# def __init__(self, data):# self.data = data# self.left = None# self.right = Nonefrom ds_v1.BinaryTree.BinaryTree import TreeNodedef max_path_sum(root):# Replace this placeholder return statement with your codereturn -1