Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Maximum Path Sum of Binary Tree Editorial

DSA Editorial, Solution and Code

Practice Problem Link: Maximum Path Sum of Binary Tree

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

A path between two nodes p and q is defined as a sequence of nodes encountered while travelling from node p to node q (or vice-versa) via parent-child connections. The path does not need to pass through the root node. The sum of the values of all these nodes in the path is considered as the path sum.

A binary tree can have multiple paths depending on the number of nodes. Thus, the path with the maximum sum is considered the maximum path sum for the tree. Note that the path can be empty, i.e. contain no nodes.

Given the reference to the root node of a binary tree, return its maximum path sum.

Naive Approach

The idea is to calculate the maximum path sums starting from each node and return the maximum value among them. This can be done as:

  • Traverse the given tree and for each node find the maximum path sum starting from that node and update the answer.
  • Now, recursively repeat this step for the left and right child of the current node.

Analysis

  • Time Complexity: O(n2)
  • Auxiliary Space Complexity: O(1)

Implementation

C++
/* This is the Node class definition

class Node {
public:
    Node* left;
    Node* right;
    int data;

    Node(int data) {
        this->left = NULL;
        this->right = NULL;
        this->data = data;
    }
};
*/
void getPathSum(Node* root, int &pathSum, int currentSum) {
	if (root == NULL) {
		return;
	}
	pathSum = max(pathSum, currentSum + root->data);
	getPathSum(root->left, pathSum, currentSum + root->data);
	getPathSum(root->right, pathSum, currentSum + root->data);
}
int getMaxPathSum(Node* root, int &maximumPath) {
	if (root == NULL) {
		return 0;
	}
	int leftSum = 0;
	int rightSum = 0;
	getPathSum(root->left, leftSum, 0);
	getPathSum(root->right, rightSum, 0);
	maximumPath = max(maximumPath, leftSum + rightSum + root->data);
	getMaxPathSum(root->left, maximumPath);
	getMaxPathSum(root->right, maximumPath);
	return maximumPath;
}
int maxPathSum(Node *root) {
    int maximumPath = INT_MIN;
	getMaxPathSum(root, maximumPath);
	return maximumPath;
}
Java
class Solution {
	/* This is the Node class definition
	
	class Node {
		public Node left;
		public Node right;
		public int data;

		public Node(int data) {
			this.data = data;
		}
	}
	*/
	static int maximumPath, pathSum;
	void getPathSum(Node root, int currentSum) {
		if (root == null) {
			return;
		}
		pathSum = Math.max(pathSum, currentSum + root.data);
		getPathSum(root.left, currentSum + root.data);
		getPathSum(root.right, currentSum + root.data);
	}
	int getMaxPathSum(Node root) {
		if (root == null) {
			return 0;
		}
		pathSum = 0;
		getPathSum(root.left, 0);
		int leftSum = pathSum;
		pathSum = 0;
		getPathSum(root.right, 0);
		int rightSum = pathSum;
		maximumPath = Math.max(maximumPath, leftSum + rightSum + root.data);
		getMaxPathSum(root.left);
		getMaxPathSum(root.right);
		return maximumPath;
	}
	int maxPathSum(Node root) {
	    maximumPath = Integer.MIN_VALUE;
		getMaxPathSum(root);
		return maximumPath;
	}
}

Optimal Approach

A node can be part of the maximum path in four ways.

  1. It is the only node in the path.
  2. The maximum path through left child + node.
  3. The maximum path through the right child + node.
  4. The maximum path through the left child + node + maximum path through the right child.

Perform a postorder traversal and consider the above four cases for each node and update the answer.

Note: The recursive function should return the maximum path sum starting from that node such that at most one child of the node is considered in the path.

Analysis

  • Time Complexity: O(n)
  • Auxiliary Space Complexity: O(1)

Implementation

C++
/* This is the Node class definition

class Node {
public:
    Node* left;
    Node* right;
    int data;

    Node(int data) {
        this->left = NULL;
        this->right = NULL;
        this->data = data;
    }
};
*/
int getMaxPathSum(Node* root, int &maximumPath) {
	if (root == NULL) {
		return 0;
	}
	int leftSum = getMaxPathSum(root->left, maximumPath);
	int rightSum = getMaxPathSum(root->right, maximumPath);
	int maxPathWithOneChild = max(root->data, max(leftSum, rightSum) + root->data);
	maximumPath = max(maximumPath, max(maxPathWithOneChild, leftSum + rightSum + root->data));
	return maxPathWithOneChild;
}
int maxPathSum(Node *root) {
    int maximumPath = INT_MIN;
	getMaxPathSum(root, maximumPath);
	return maximumPath;
}
Java
class Solution {
	/* This is the Node class definition
	
	class Node {
		public Node left;
		public Node right;
		public int data;

		public Node(int data) {
			this.data = data;
		}
	}
	*/
	static int maximumPath;
	int getMaxPathSum(Node root) {
		if (root == null) {
			return 0;
		}
		int leftSum = getMaxPathSum(root.left);
		int rightSum = getMaxPathSum(root.right);
		int maxPathWithOneChild = Math.max(root.data, Math.max(leftSum, rightSum) + root.data);
		maximumPath = Math.max(maximumPath, Math.max(maxPathWithOneChild, leftSum + rightSum + root.data));
		return maxPathWithOneChild;
	}
	int maxPathSum(Node root) {
	    maximumPath = Integer.MIN_VALUE;
		getMaxPathSum(root);
		return maximumPath;
	}
}
Related Content
Balanced Binary Tree
Binary Search Tree (BST) Iterator
Binary Tree to Doubly Linked List
Binary Tree Inorder Traversal
Binary Tree Postorder Traversal
Binary Tree Preorder Traversal
Bottom View of Binary Tree
Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Preorder and Inorder Traversal
Delete Node in a Binary Search Tree (BST)
Diameter of Binary Tree
Flatten Binary Tree to Linked List
Identical Binary Trees
Inorder Predecessor of Node in BST
Inorder Successor of Node in BST
Insert into a Binary Search Tree (BST)
Invert Binary Tree
Is Binary Tree BST
Kth Largest in BST
Kth Smallest in BST
Left View of Binary Tree
Level Order of Binary Tree
Lowest Common Ancestor in Binary Tree
Lowest Common Ancestor in BST
Maximum Depth of Binary Tree
Populating Next Right Pointers in Each Node
Right View of Binary Tree
Search in a Binary Search Tree (BST)
Serialize and Deserialize Binary Search Tree (BST)
Size of the Largest BST in a Binary Tree
Symmetric Binary Tree
Top View of Binary Tree
Two Sum in BST
Binary Tree Zigzag Level Order Traversal
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet