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 constructor(val, left = null, right = null) {
3 this.val = (val===undefined ? 0 : val);
4 this.left = (left===undefined ? null : left);
5 this.right = (right===undefined ? null : right);
6 }
7}
8
9function diameterOfBinaryTree(root) {
10 let diameter = 0;
11 function dfs(node) {
12 if (node === null) {
13 return 0;
14 }
15 const left = dfs(node.left);
16 const right = dfs(node.right);
17 diameter = Math.max(diameter, left + right);
18 return Math.max(left, right) + 1;
19 }
20 dfs(root);
21 return diameter;
22}
The JavaScript function uses closures to maintain the diameter
variable within its scope. The dfs
utility function computes subtree heights and continually updates the diameter. The function diameterOfBinaryTree
calls this utility on the tree's root.
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
Memoization is implemented using an auxiliary array memo
, which stores the height of each node index as calculated by DFS to avoid redundant computations. TreeNode indexing assumes a complete binary tree structure for simplicity in accessing child indices.