forked from qcha/JBook
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
# Максимальная сумма значений ветки дерева | ||
|
||
## Условие | ||
|
||
Дано бинарное дерево, каждая вершина которого это: | ||
|
||
```java | ||
class TreeNode { | ||
int value; | ||
TreeNode left; | ||
TreeNode right; | ||
} | ||
``` | ||
|
||
Требуется написать метод, который найдет максимальную сумму значений ветки. На вход подается корень бинарного дерева. Метод должен вернуть целое число - максимальную сумму значений ветки бинарного дерева. | ||
|
||
## Решение | ||
|
||
```java | ||
public class TreeNode { | ||
int value; | ||
TreeNode left; | ||
TreeNode right; | ||
|
||
public static int maxSum(TreeNode root) { | ||
if (root == null) { | ||
return 0; | ||
} | ||
|
||
return root.value + Math.max(sum(root.left), sum(root.right)); | ||
} | ||
} | ||
``` | ||
|
||
При работе с бинарными деревьями и подсчете их высоты, основная идея заключается в использовании рекурсии. | ||
|
||
Идея в том, чтобы "посчитать" сумму значений каждой ветки, а после взять наибольшую. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters