mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
cs: add “1161. Maximum Level Sum of a Binary Tree”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
5dded1796b
commit
f96b066323
1 changed files with 43 additions and 0 deletions
43
cs/maximum-level-sum-of-a-binary-tree.cs
Normal file
43
cs/maximum-level-sum-of-a-binary-tree.cs
Normal file
|
@ -0,0 +1,43 @@
|
|||
/**
|
||||
* Definition for a binary tree node.
|
||||
* public class TreeNode {
|
||||
* public int val;
|
||||
* public TreeNode left;
|
||||
* public TreeNode right;
|
||||
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
|
||||
* this.val = val;
|
||||
* this.left = left;
|
||||
* this.right = right;
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
public class Solution {
|
||||
private void MaxSum(List<int> levels, int level, TreeNode node) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (level >= levels.Count) {
|
||||
levels.Add(0);
|
||||
}
|
||||
levels[level] += node.val;
|
||||
|
||||
MaxSum(levels, level + 1, node.left);
|
||||
MaxSum(levels, level + 1, node.right);
|
||||
}
|
||||
|
||||
public int MaxLevelSum(TreeNode root) {
|
||||
var levels = new List<int>();
|
||||
|
||||
MaxSum(levels, 0, root);
|
||||
|
||||
var maxIdx = 0;
|
||||
for (var i = 1; i < levels.Count; ++i) {
|
||||
if (levels[i] > levels[maxIdx]) {
|
||||
maxIdx = i;
|
||||
}
|
||||
}
|
||||
|
||||
return maxIdx + 1;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue