Topic category
binary tree
Link to original title
Given a binary tree, you need to calculate its diameter length. The diameter of a binary tree is the maximum of the lengths of the paths between any two nodes. This path may or may not pass through the root node.
Code case: 1
/
2 3
/ \
4 5
Returns 3, whose length is the path [4,2,1,3] or [5,2,1,3].
answer
/**
* 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;
* }
* }
*/
class Solution {
int ans = 0 ;
public int diameterOfBinaryTree(TreeNode root) {
dfs(root);
return ans ;
}
public int dfs(TreeNode root){
if(root == null) return 0 ;
int left = dfs(root.left);
int right = dfs(root.right);
ans = Math.max(ans , left + right );
return Math.max(left ,right)+1;
}
}