Binary tree? And the maximum path!
Title:
Given a non-empty binary tree, and returns its maximum path.
In this problem, it is defined as a path from any node in the tree, to the sequence of any node. The path includes at least one node, and not necessarily through the root node.
Examples
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20, null, null, 15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
Topic analysis
- Goal: to find a path in a binary tree node and its maximum ⇒
For a node
to go forward node ⇒ left / right node
path and the current node value + = residual path (to the left node / right starting node) and node values recursive ⇒
Problem-solving ideas
variable | effect |
---|---|
find() | To find the path and |
process
- The binary tree root in the queue s
- ⇒ looking for a node to go to the left (to the left node as a starting point) and + right path to go (to the right node as a starting point) path and
- Determining whether to update the path with the maximum
- The left node is queued repeated 2,3 s
code show as below
int find(TreeNode*root) //寻找 root 为起点的最大路径结点和
{
if(!root) return 0;
int left = 0, right = 0;
if(!root->left && !root->right) return root->val;
if(root -> left) left += find(root->left);
if(root -> right) right += find(root->right);
return max(max(root->val,root->val+left),root->val+right);
}
class Solution {
public:
int maxPathSum(TreeNode* root) {
if(!root) return 0;
int max0 = root->val;
queue<TreeNode*> s{{root}};
while(!s.empty())
{
TreeNode* temp = s.front();
s.pop();
int left = find(temp->left); //向左走
int right = find(temp->right); //向右走
max0 = max(max(max(temp->val,temp->val+left),max(temp->val+right,temp->val+left+right)),max0); //判断是否更新最大值
if(temp->left) s.push(temp->left);
if(temp->right) s.push(temp->right);
}
return max0;
}
};