Skip to content

2583. Kth Largest Sum in a Binary Tree #735

Answered by kovatz
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We'll follow these steps:

  1. Level Order Traversal: We will use a Breadth-First Search (BFS) to traverse the tree level by level.
  2. Calculate Level Sums: During the BFS traversal, we'll calculate the sum of node values at each level.
  3. Sort and Find k-th Largest Sum: After calculating the sums for all levels, we'll sort the sums and retrieve the k-th largest value.

Let's implement this solution in PHP: 2583. Kth Largest Sum in a Binary Tree

<?php
// Definition for a binary tree node.
class TreeNode {
    public $val;
    public $left;
    public $right;
    public function __construct($val = 0, $left = null, $right = null) {
        $this->val = $val;
        $this->left = $left;
        $this->

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Oct 22, 2024
Maintainer Author

@kovatz
Comment options

kovatz Oct 22, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants