2024/9/3 Hot100 binaryTree 最后一题

This commit is contained in:
linlihong 2024-09-03 10:01:27 +08:00
parent 8fc3fadc94
commit 9cadfd058d
2 changed files with 37 additions and 5 deletions

View File

@ -0,0 +1,31 @@
package com.cool.hot100.binary_tree;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/03/09:37
* DayNumber 1
* Hard 3
* Level ?
*/
public class Num124 {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return res;
}
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));
res = Math.max(res, root.val + left + right);
return root.val + Math.max(left,right);
}
}

View File

@ -11,20 +11,21 @@ package com.cool.hot100.binary_tree;
*/ */
public class Num543 { public class Num543 {
int max=0; int max = 0;
public int diameterOfBinaryTree(TreeNode root) { public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0; if (root == null) return 0;
int left = getTreeDeep(root.left); int left = getTreeDeep(root.left);
int right = getTreeDeep(root.right); int right = getTreeDeep(root.right);
return Math.max(max,left+right); return Math.max(max, left + right);
} }
private int getTreeDeep(TreeNode root) { private int getTreeDeep(TreeNode root) {
if (root == null) return 0; if (root == null) return 0;
int left = getTreeDeep(root.left); int left = getTreeDeep(root.left);
int right=getTreeDeep(root.right); int right = getTreeDeep(root.right);
max = Math.max(max,left+right ); max = Math.max(max, left + right);
return Math.max(left,right)+1; return Math.max(left, right) + 1;
} }
} }