I. TopicsBinary Tree Maximum Path SumTotal Accepted: 41576 Total Submissions: 193606 My Submissions
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / 2 3
Return 6
.
Show TagsHas you met this question in a real interview? Yes No
Discuss
two. Problem solving skillsThis question is still a depth-first search for the two-fork tree, but there are a couple of questions to consider when traversing, the maximum path and the path that may be in series with the left and right subtree of the root node, or the tree or the subtree with the root node, so in the recursive process, consider both of these issues. This allows you to find the maximum path and in the recursive process. The time complexity and spatial complexity of the problem is the same as the normal two-tree depth first search, the time complexity is O (n), and the spatial complexity is O (logn).
Three. Implementing the Code
#include <iostream> #include <vector> #include <climits>using std::vector;/*** Definition for a binary Tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode (int x): Val (x), left (null), right (null) {}*};*/struct treenode{int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (null) {}};class solution{private:int maxpathsum (TreeNode *root, int &r Esult) {if (!root) {return 0; } int rootresult = root->val; int leftresult = Maxpathsum (Root->left, Result); int rightresult = Maxpathsum (Root->right, Result); Leftresult = Leftresult * (Leftresult > 0); Rightresult = Rightresult * (Rightresult > 0); All the tree int tmpresult = rootresult + Leftresult + rightresult; if (Result < Tmpresult) {result = Tmpresult; }//Only left subtree or tHe right subtree Tmpresult = Rootresult + (Leftresult > Rightresult? Leftresult:rightresult); if (Result < Tmpresult) {result = Tmpresult; } return Tmpresult; }public:int maxpathsum (treenode* root) {int Result = int_min; Maxpathsum (Root, Result); return Result; }};
Four. ExperienceThis problem is also a binary tree depth search for a variant, the main difficulty is to investigate the largest path and may appear in the entire subtree, may also appear in the left subtree or right subtree, but only these two situations need to be considered, there is no need to consider other situations.
Copyright, welcome reprint, reproduced Please indicate the source, thank you
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode_binary Tree Maximum Path Sum