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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13 private int diameter = 0;
14 private int DFS(TreeNode node) {
15 if (node == null) return 0;
16 int left = DFS(node.left);
17 int right = DFS(node.right);
18 diameter = Math.Max(diameter, left + right);
19 return Math.Max(left, right) + 1;
20 }
21 public int DiameterOfBinaryTree(TreeNode root) {
22 DFS(root);
23 return diameter;
24 }
25}
In C# implementation, the diameter is maintained as a private member variable. The recursive method DFS
traverses each node, calculates heights, and updates the global diameter. The main method DiameterOfBinaryTree
initiates the DFS procedure.
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#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> memo;
int diameter;
int dfs(TreeNode* root, int node_idx) {
if (!root) return 0;
if (memo[node_idx] != -1) return memo[node_idx];
int left = dfs(root->left, node_idx * 2 + 1);
int right = dfs(root->right, node_idx * 2 + 2);
diameter = max(diameter, left + right);
memo[node_idx] = max(left, right) + 1;
return memo[node_idx];
}
int diameterOfBinaryTree(TreeNode* root) {
if (!root) return 0;
memo.assign(10000, -1);
diameter = 0;
dfs(root, 0);
return diameter;
}
};
C++ introduces an auxiliary vector memo
to help memoize heights of subtrees to prevent repetitive recalculative operations, especially effective in uniformly structured trees.