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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Maximum XOR path of a Binary Tree
- Find the maximum path sum between two leaves of a binary tree
- Maximum Consecutive Increasing Path Length in Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Count of 1's in any path in a Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Minimum sum path between two leaves of a binary tree
- Print all Coprime path of a Binary Tree
- Print path between any two nodes in a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Longest Path with Same Values in a Binary Tree
- Maximum XOR with given value in the path from root to given node in the tree
- Sort the path from root to a given node in a Binary Tree
- Print path from root to a given node in a binary tree
- Find all root to leaf path sum of a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Shortest path between two nodes in array like representation of binary tree
Improved By : Rajput-Ji