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.
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode(int x) { val = x; }
6}
7
8class Solution {
9 int diameter = 0;
10 public int dfs(TreeNode node) {
11 if (node == null) return 0;
12 int left = dfs(node.left);
13 int right = dfs(node.right);
14 diameter = Math.max(diameter, left + right);
15 return Math.max(left, right) + 1;
16 }
17 public int diameterOfBinaryTree(TreeNode root) {
18 dfs(root);
19 return diameter;
20 }
21}
In the Java solution, we use a class member variable diameter
initialized to zero. The dfs
computes the height of left and right children, updating the diameter when necessary. The public method diameterOfBinaryTree
initiates the DFS with the root node.
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
Python uses a dictionary memo
to enhance the DFS approach by storing previously computed heights, optimizing the time taken, especially for larger trees with nested levels and recurring patterns.