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 sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Find the maximum sum leaf to root path in a Binary Tree
- Find the maximum path sum between two leaves of a binary tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Maximum Consecutive Increasing Path Length in Binary Tree
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Maximum XOR path of a Binary Tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Minimum sum path between two leaves of a binary tree
- Find all root to leaf path sum of a Binary Tree
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Convert a Generic Tree(N-array Tree) to Binary Tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Minimum swap required to convert binary tree to binary search tree
Improved By : Rajput-Ji