543. Diameter of Binary Tree - E
124. Maximum Path Sum in Binary Tree
These three questions use the same routine: recursion
PS: When it comes to the most value position related to the binary tree, DFS is generally used.
1. Binary tree diameter
Concept: The diameter length of a binary tree is the maximum value of any two node path lengths
1.1 Solution
Traverse each node, calculate the longest path (left subtree path + right subtree path) centered on each node, and update the global maximum path.
class Solution{
int maxDiameter = 0 ;
public int diameterOfBinaryTree(TreeNode root){
if(root == null){
return 0;
}
}
public int dfs(TreeNode root){
if(root.left == null && root.right == null){
return 0;
}
int leftDiameter = (root.left == null ) ? 0 : dfs(root.left) + 1;
int rightDiameter = (root.right == null) ? 0 : dfs(root.right) + 1;
maxDiameter = Math.max(maxDiameter,leftDiameter + rightDiameter);
return Math.max(leftDiameter,rightDiameter);
}
}
2. The longest equal value path
Given a binary tree, find the longest path where every node in this path has the same value . This path may or may not pass through the root node.
2.1 Solution
class Solution{
int maxPath = 0;
public int longestUnivaluePath(TreeNode root){
if(root == null){
return 0;
}
dfs(root);
return maxPath;
}
public int dfs(TreeNode root){
if(root.left == null && root.right == null){
return 0;
}
int leftPath = (root.left == null) ? 0 : dfs(root.left) + 1;
int rightPath = (root.right == null) ? 0 dfs(root.right) + 1;
/**
* 题目要求每个节点是相同值。故如果当前节点和其左,右子节点的值不同,则将其路径重新赋值0
*/
if(leftPath > 0 && root.left.val != root.val){
leftPath = 0;
}
if(rightPath > 0 && root.right.val != root.val){
rightPath = 0;
}
maxPath = Math.max(maxPath,leftPath + rightPath);
return Math.max(leftPath,rightPath);
}
}
3. The maximum path sum of the binary tree
Path : A sequence starting from any node in the tree, following the parent node-child node connection, and reaching any node. The same node can appear at most once in a path sequence.
Path sum : the sum of the values of each node in the path.
The maximum path sum sought in the title .
3.1 Solution
class Solution{
// 这里因为有负数的存在,最大值要设置为最小值。
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root){
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root == null) return 0;
// 求最大路径和,故舍弃左,右孩子的路径和为负的情况。
int left = Math.max(0,dfs(root.left));
int right = Math.max(0,dfs(root.right));
max = Math.max(max,left + right + root.val);
return Math.max(left,right) + root.val;
}
}