classSolution {int res =0;publicintdiameterOfBinaryTree(TreeNode root) {maxLength(root);return res; }privateintmaxLength(TreeNode root) {if (root ==null) return0;int left =maxLength(root.left);int right =maxLength(root.right); res =Math.max(res, left + right); // maybe not walk through root, so record here againreturnMath.max(left, right) +1; // walk through root }}
new ver
naive, we can do bfs on each node: O(n^2)
right ver, dfs
T: O(n)
S: O(h), worst O(n)
classSolution {int numOfNodes =0;publicintdiameterOfBinaryTree(TreeNode root) {dfs(root);return numOfNodes-1; // len is num of nodes - 1 }privateintdfs(TreeNode node) {if (node ==null) {return0; }int left =dfs(node.left);int right =dfs(node.right);// res = left side node num + right side node num + node itself numOfNodes =Math.max(numOfNodes, left+right+1); // one side's longer length(node num) + node itselfreturnMath.max(left, right)+1; }}
without global variable
```java/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * }length of the diameter of the tree = max (left depth + right depth) */classSolution {publicintdiameterOfBinaryTree(TreeNode root) {int[] result =newint[1];dfs(root, result);return result[0]; }privateintdfs(TreeNode node,int[] result) {if (node ==null) {return0; }int left =dfs(node.left, result);int right =dfs(node.right, result); result[0] =Math.max(result[0], left + right);returnMath.max(left, right) +1; }}```