515. Find Largest Value in Each Tree Row #998
-
Topics: Given the Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem "Find Largest Value in Each Tree Row" requires identifying the largest value present at each level (row) of a binary tree. Given a binary tree, the goal is to traverse the tree row by row and collect the maximum value from each row. This problem involves fundamental tree traversal techniques such as Breadth-First Search (BFS) or Depth-First Search (DFS). Key Points
ApproachThe most straightforward approach to finding the largest value in each row is using BFS:
Alternatively, DFS can also be used:
Plan
Solution Steps
Let's implement this solution in PHP: 515. Find Largest Value in Each Tree Row <?php
// Definition for a binary tree node.
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
/**
* @param TreeNode $root
* @return Integer[]
*/
function largestValues($root) {
if ($root === null) return [];
$queue = [$root];
$result = [];
while (!empty($queue)) {
$levelSize = count($queue);
$maxValue = PHP_INT_MIN;
for ($i = 0; $i < $levelSize; $i++) {
$currentNode = array_shift($queue);
$maxValue = max($maxValue, $currentNode->val);
if ($currentNode->left !== null) {
$queue[] = $currentNode->left;
}
if ($currentNode->right !== null) {
$queue[] = $currentNode->right;
}
}
$result[] = $maxValue;
}
return $result;
}
// Example usage:
$root = new TreeNode(1);
$root->left = new TreeNode(3);
$root->right = new TreeNode(2);
$root->left->left = new TreeNode(5);
$root->left->right = new TreeNode(3);
$root->right->right = new TreeNode(9);
print_r(largestValues($root)); // Output: [1, 3, 9]
?> Explanation:Input:
|
Beta Was this translation helpful? Give feedback.
The problem "Find Largest Value in Each Tree Row" requires identifying the largest value present at each level (row) of a binary tree. Given a binary tree, the goal is to traverse the tree row by row and collect the maximum value from each row. This problem involves fundamental tree traversal techniques such as Breadth-First Search (BFS) or Depth-First Search (DFS).
Key Points