当前位置:网站首页>LeetCode 515(C#)

LeetCode 515(C#)

2022-07-07 19:17:00 Just be interesting

List of articles

subject

Given the root node of a binary tree root , Please find the maximum value of each layer in the binary tree .

Example 1:
Input : root = [1,3,2,5,3,null,9]
Output : [1,3,9]

Example 2:
Input : root = [1,2,3]
Output : [1,3]

Code

  • DFS
public class Solution 
{
    
    public IList<int> LargestValues(TreeNode root) 
    {
    
        List<int> list = new List<int>();
        Dfs(list, root, 0);
        return list;
    }

    private void Dfs(IList<int> list, TreeNode node, int depth)
    {
    
        if (node == null) return;
        if (depth >= list.Count) list.Add(node.val);
        else list[depth] = Math.Max(list[depth], node.val);

        Dfs(list, node.left, depth + 1);
        Dfs(list, node.right, depth + 1);
    }
}
  • BFS
public class Solution 
{
    
    public IList<int> LargestValues(TreeNode root) 
    {
    
        List<int> list = new List<int>();

        Queue<TreeNode> queue = new Queue<TreeNode>();
        if (root != null) queue.Enqueue(root);
        while (queue.Count > 0)
        {
    
            (int sz, int ans) = (queue.Count, int.MinValue);
            for (int i = 0; i < sz; i++)
            {
    
                var t = queue.Dequeue();
                ans = Math.Max(ans, t.val);

                if (t.left != null) queue.Enqueue(t.left);
                if (t.right != null) queue.Enqueue(t.right);
            }
            list.Add(ans);
        }

        return list;
    }
}
原网站

版权声明
本文为[Just be interesting]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071515233588.html