Files
obsidian/АиСД/Задачи/LeetCode/Binary Tree Maximum Path Sum.md
T
roma-dxunvrs f57762fd3b Init
2026-09-03 21:40:46 +03:00

24 lines
877 B
Markdown

Leetcode #124 | #Hard | [[Деревья]] | [[DFS]]
## Идея
dfs + отбрасываем отрицательные пути
## [[Big-O]]
- Время ```O(N)```
- Память ```O(H)```
N - кол-во узлов, H -высота дерева
## Код
```Java
class Solution {
private int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return res;
}
private int dfs(TreeNode node) {
if (node == null) return 0;
int left = Math.max(0, dfs(node.left)); // путь в левой ветке
int right = Math.max(0, dfs(node.right)); // путь в правой ветке
res = Math.max(res, node.val + left + right); // итоговый путь через вершину
return node.val + Math.max(left, right); // максимальный путь вниз
}
}
```