2
// Declare Global Variable ans to 05
// Depth First Search Function6
public int dfs(TreeNode root) {7
if (root == null) return 0;8
// recursive call for left height9
int lh = dfs(root.left);10
// recursive call for right height11
int rh = dfs(root.right);14
ans = Math.max(ans, lh + rh);17
return Math.max(lh, rh) + 1;20
// Diameter of Binary Tree Function21
public int diameterOfBinaryTree(TreeNode root) {30
Input: root = [1,2,3,4,5]32
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].35
// Time & Space Complexity -