Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.
Input: Root of below tree 1 / \ 2 3 Output: 6 See below diagram for another example. 1+2+3
For each node there can be four ways that the max path goes through the node:
1. Node only
2. Max path through Left Child + Node
3. Max path through Right Child + Node
4. Max path through Left Child + Node + Max path through Right Child
The idea is to keep trace of four paths and pick up the max one in the end. An important thing to note is, root of every subtree need to return maximum path sum such that at most one child of root is involved. This is needed for parent function call. In below code, this sum is stored in ‘max_single’ and returned by the recursive function.
Max path sum is 42
Time Complexity: O(n) where n is number of nodes in Binary Tree.
This article is contributed by Anmol Varshney (FB Profile: https://www.facebook.com/anmolvarshney695). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Maximum XOR path of a Binary Tree
- Find the maximum path sum between two leaves of a binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Maximum Consecutive Increasing Path Length in Binary Tree
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Count of 1's in any path in a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Print all Coprime path of a Binary Tree
- Minimum sum path between two leaves of a binary tree
- Longest Path with Same Values in a Binary Tree
- Print path between any two nodes in a Binary Tree
- Maximum XOR with given value in the path from root to given node in the tree
- Print path from root to a given node in a binary tree
- Sort the path from root to a given node in a Binary Tree
- Print path from root to all nodes in a Complete Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
Improved By : Rajput-Ji