C# || How To Find Largest Value In Each Binary Tree Row Using C#
The following is a module with functions which demonstrates how to find the largest value in each binary tree row using C#.
1. Largest Values – Problem Statement
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
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]
2. Largest Values – Solution
The following is a solution which demonstrates how to find the largest value in each binary tree row.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 28, 2023 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find the largest value binary tree row // ============================================================================ /** * 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 { public IList<int> LargestValues(TreeNode root) { if (root == null) { return new List<int>(); } var ans = new List<int>(); var queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count > 0) { int currMax = int.MinValue; for (int i = queue.Count -1; i >= 0; --i) { var node = queue.Dequeue(); currMax = Math.Max(currMax, node.val); if (node.left != null) { queue.Enqueue(node.left); } if (node.right != null) { queue.Enqueue(node.right); } } ans.Add(currMax); } return ans; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
[1,3,9]
[1,3]
Leave a Reply