2458. Height of Binary Tree After Subtree Removal Queries #751
-
Topics: You are given the You have to perform
Return an array Note:
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The solution employs a two-pass approach:
Code Breakdown1. Class Definition and Properties: class Solution {
private $valToMaxHeight = [];
private $valToHeight = [];
2. Main Function: function treeQueries($root, $queries) {
$this->height($root);
$this->dfs($root, 0, 0);
$answer = [];
foreach ($queries as $query) {
$answer[] = $this->valToMaxHeight[$query];
}
return $answer;
}
3. Height Calculation: private function height($node) {
if ($node === null) {
return 0;
}
if (isset($this->valToHeight[$node->val])) {
return $this->valToHeight[$node->val];
}
$leftHeight = $this->height($node->left);
$rightHeight = $this->height($node->right);
$this->valToHeight[$node->val] = 1 + max($leftHeight, $rightHeight);
return $this->valToHeight[$node->val];
}
4. Depth-First Search for Maximum Height: private function dfs($node, $depth, $maxHeight) {
if ($node === null) {
return;
}
$this->valToMaxHeight[$node->val] = $maxHeight;
// Update heights for left and right subtree
$leftHeight = isset($this->valToHeight[$node->right->val]) ? $this->valToHeight[$node->right->val] : 0;
$rightHeight = isset($this->valToHeight[$node->left->val]) ? $this->valToHeight[$node->left->val] : 0;
// Recursive DFS call for left and right subtrees
$this->dfs($node->left, $depth + 1, max($maxHeight, $depth + $leftHeight));
$this->dfs($node->right, $depth + 1, max($maxHeight, $depth + $rightHeight));
}
Example WalkthroughLet's go through an example step-by-step. Example Input: // Tree Structure
// 1
// / \
// 3 4
// / / \
// 2 6 5
// \
// 7
$root = [1, 3, 4, 2, null, 6, 5, null, null, null, null, null, 7];
$queries = [4]; Initial Height Calculation:
After the height computation, $valToHeight = [
1 => 3,
2 => 0,
3 => 2,
4 => 2,
5 => 0,
6 => 1,
7 => 0
]; DFS for Max Heights:
Result Array After Queries:
Final OutputThe result for the input provided will be: // Output
[2] This structured approach ensures that we efficiently compute the necessary heights and answer each query in constant time after the initial preprocessing. The overall complexity is O(n + m), where n is the number of nodes in the tree and m is the number of queries. |
Beta Was this translation helpful? Give feedback.
The solution employs a two-pass approach:
Code Breakdown
1. Class Definition and Properties:
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: