
这题很简单,用递归或迭代找每一层的和,再找其中最大的即可。递归更好理解,也较容易实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<int> list = new List<int>();
public int MaxLevelSum(TreeNode root) {
InitList(root,0);
int max = int.MinValue;
int index = -1;
for(int i = 0; i < list.Count(); i++)
{
if(list[i] > max)
{
max = list[i];
index = i;
}
}
return index+1;
}
private void InitList(TreeNode t, int d)
{
if(t == null)
return;
if(list.Count() < d+1)
list.Add(0);
list[d] += t.val;
InitList(t.left,d+1);
InitList(t.right,d+1);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int MaxLevelSum(TreeNode root)
{
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int max = int.MinValue;
int maxIndex = -1;
int sizeF = 1;
int sizeS = 0;
int hadCount = 0;
int currSum = 0;
int index = 1;
while(queue.Count() > 0)
{
TreeNode t = queue.Dequeue();
hadCount ++;
currSum += t.val;
if(t.left != null)
{
queue.Enqueue(t.left);
sizeS ++;
}
if(t.right != null)
{
queue.Enqueue(t.right);
sizeS ++;
}
if(hadCount == sizeF)
{
sizeF = sizeS;
sizeS = 0;
Console.WriteLine(index+":"+currSum);
if(currSum > max)
{
max = currSum;
maxIndex = index;
}
currSum = 0;
index ++;
hadCount = 0;
}
}
return maxIndex;
}
}
本文介绍了一种算法,用于找到二叉树中具有最大节点和的层,并提供了两种实现方式:递归和迭代。递归方法更易于理解和实现,而迭代方法使用队列进行层级遍历。
370

被折叠的 条评论
为什么被折叠?



