# Question 20: The diameter of the binary tree

Posted on Aug. 10, 2023, noon by Tushar Sunder

Category:
LeetCode Personal Problem Solving Summary
Tag:
LeetCode Personal Problem Solving Summary
Important: The diameter of a binary tree is the maximum number of nodes formed by the left and right subtrees and the root node minus one. Set an intermediate variable Max, and compare the number of nodes formed by left and right subtrees and root nodes with Max each time. Save the larger node with Max until the longest node path formed by all left and right subtrees and root nodes is Max, and the maximum diameter is Max with max-1 finally. And the essence of this problem is to find the depth of the tree.

`class Solution { int max = Integer.MIN_VALUE; public int diameterOfBinaryTree(TreeNode root) { depth(root); return max - 1; } public int depth(TreeNode root){ if(root == null) return 0; int l = depth(root.left); int r = depth(root.right); max = Math.max(max,l + r + 1); return Math.max(l,r) + 1; }}`