
Sponsored
Sponsored
This approach involves a DFS traversal of the tree. For each node, we compute the number of leaf nodes at each possible distance. We merge the results from the left and right subtrees and count the valid leaf pairs.
Time Complexity: O(n * distance) due to traversing the entire tree and computing leaf pairs.
Space Complexity: O(distance) for storing distance arrays.
1function TreeNode(val) {
2 this.val = val;
3 this.left = this.right = null;
4}
5
6var countPairs = function(root, distance) {
7 let result = 0;
8
9 function dfs(node) {
10 if (!node) return Array(distance + 1).fill(0);
11 if (!node.left && !node.right) {
12 let leaves = Array(distance + 1).fill(0);
13 leaves[1] = 1;
14 return leaves;
15 }
16
17 let left = dfs(node.left);
18 let right = dfs(node.right);
19
20 for (let i = 1; i <= distance; i++) {
21 for (let j = 1; j <= distance - i; j++) {
22 result += left[i] * right[j];
23 }
24 }
25
26 let leaves = Array(distance + 1).fill(0);
27 for (let i = 1; i < distance; i++) {
28 leaves[i + 1] = left[i] + right[i];
29 }
30
31 return leaves;
32 }
33
34 dfs(root);
35 return result;
36};JavaScript similarly uses arrays to manage distances at each node. Each leaf node is managed with an individual distance array, allowing easy combination and analysis during traversal.
This approach leverages preprocessing leaf distances in a dynamic programming table, which gives quick lookups during pair evaluation. It builds the DP table during a DFS traversal, allowing efficient pair computation afterward.
Time Complexity: Approximately O(n^2) for thorough pairing and evaluation.
Space Complexity: O(n^2) due to pair-wise distance visualization.
1/* This solution is based on C and would implement a similar strategy to preprocess and calculate distances between all leaves, followed by evaluating valid pairs. For brevity, a sample plan is provided without full implementation due to competition space. */A solution in C would involve more detailed memory management and array calculations for storing and evaluating distances.