Last updated on October 5th, 2024 at 04:20 pm
Here, We see Find Largest Value in Each Tree Row LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
String
Companies
Level of Question
Medium
Find Largest Value in Each Tree Row LeetCode Solution
Table of Contents
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]
1. Find Largest Value in Each Tree Row LeetCode Solution C++
class Solution { public: vector<int> largestValues(TreeNode* root) { if (!root) return {}; vector<int> result; queue<TreeNode*> queue; queue.push(root); while (!queue.empty()) { int curr_level_size = queue.size(); int max_val = INT_MIN; for (int i = 0; i < curr_level_size; ++i) { TreeNode* node = queue.front(); queue.pop(); max_val = std::max(max_val, node->val); if (node->left) queue.push(node->left); if (node->right) queue.push(node->right); } result.push_back(max_val); } return result; } };
2. Find Largest Value in Each Tree Row Solution Java
class Solution { public List<Integer> largestValues(TreeNode root) { if (root == null) return new ArrayList<>(); List<Integer> result = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int curr_level_size = queue.size(); int max_val = Integer.MIN_VALUE; for (int i = 0; i < curr_level_size; i++) { TreeNode node = queue.poll(); max_val = Math.max(max_val, node.val); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } result.add(max_val); } return result; } }
3. Find Largest Value in Each Tree Row Solution JavaScript
var largestValues = function(root) { if (!root) return []; const result = []; const queue = [root]; while (queue.length) { let curr_level_size = queue.length; let max_val = Number.MIN_SAFE_INTEGER; for (let i = 0; i < curr_level_size; i++) { const node = queue.shift(); max_val = Math.max(max_val, node.val); if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } result.push(max_val); } return result; };
4. Find Largest Value in Each Tree Row Solution Python
class Solution(object): def largestValues(self, root): if not root: return [] result = [] queue = deque([root]) while queue: curr_level_size = len(queue) max_val = float('-inf') for _ in range(curr_level_size): node = queue.popleft() max_val = max(max_val, node.val) for child in [node.left, node.right]: if child: queue.append(child) result.append(max_val) return result