Skip to content

2458. Height of Binary Tree After Subtree Removal Queries #751

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

You must be logged in to vote

The solution employs a two-pass approach:

  1. Calculate the height of each node in the tree.
  2. Determine the maximum height of the tree after removing the subtree rooted at each queried node.

Code Breakdown

1. Class Definition and Properties:

class Solution {

    private $valToMaxHeight = [];
    private $valToHeight = [];
  • valToMaxHeight: This array will store the maximum height of the tree after removing each node's subtree.
  • valToHeight: This array will store the height of each node's subtree.

2. Main Function:

function treeQueries($root, $queries) {
    $this->height($root);
    $this->dfs($root, 0, 0);

    $answer = [];
    foreach ($queries as $query) {
        $answer[] = $this->valT…

Replies: 1 comment 2 replies

Comment options

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

mah-shamim Oct 26, 2024
Maintainer Author

@kovatz
Comment options

kovatz Oct 26, 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 hard Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants