1161. 最大层内元素和

本文介绍了一种算法,用于找到二叉树中具有最大节点和的层,并提供了两种实现方式:递归和迭代。递归方法更易于理解和实现,而迭代方法使用队列进行层级遍历。

这题很简单,用递归或迭代找每一层的和,再找其中最大的即可。递归更好理解,也较容易实现。

/**
 * 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;


    }

}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值