Sponsored
Sponsored
This approach uses a depth-first search (DFS) to calculate the diameter of the binary tree. The key idea is to determine the longest path passing through each node and update the maximum diameter accordingly.
By computing the height of the left and right subtrees at each node, we can obtain the potential diameter passing through that node as the sum of the heights plus one. We will keep track of the global diameter, updating it as necessary.
Time Complexity: O(N), where N is the number of nodes. Each node is visited once.
Space Complexity: O(H), where H is the height of the tree, representing the call stack size due to recursion.
1#include <algorithm>
2using namespace std;
3
4struct TreeNode {
5 int val;
6 TreeNode *left;
7 TreeNode *right;
8 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9};
10
11class Solution {
12public:
13 int diameter;
14 int dfs(TreeNode* root) {
15 if (!root) return 0;
16 int left = dfs(root->left);
17 int right = dfs(root->right);
18 diameter = max(diameter, left + right);
19 return max(left, right) + 1;
20 }
21 int diameterOfBinaryTree(TreeNode* root) {
22 diameter = 0;
23 dfs(root);
24 return diameter;
25 }
26};
We define a member variable diameter
in the Solution
class to keep track of the maximum diameter. The dfs
method calculates the height of the left and right subtrees recursively and updates the diameter
for each node as the sum of the heights of its subtrees. The diameterOfBinaryTree
function starts the recursion.
This method enhances the recursive DFS approach by incorporating memoization for subtree height calculations, thereby eliminating redundant computations and improving performance, especially beneficial for trees with high duplication of node structures.
Time Complexity: Approaches O(N) due to controlled redundant calculations via memoization.
Space Complexity: O(N) for storing the heights in the memo array.
1
The Java approach makes use of a HashMap
to cache results for subtree heights, facilitating a more dynamic and memory-efficient method for differential subtree configurations, prioritizing reusability.