👨🏫 题目地址
一个节点的最大直径 = 它左树的深度 + 它右树的深度
😋 AC code
/*** 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){if (root == null)return ans;calDepth(root);return ans;}// 计算 root 的深度(从 1 开始)private int calDepth(TreeNode root){int res = 0;if (root == null)return 0;int l = calDepth(root.left);//左子树的最大深度int r = calDepth(root.right);//右子树的最大深度ans = Math.max(ans, l + r);//以当前 root 为转折点的最大直径长度return Math.max(l, r) + 1;//当前树的深度 = 左、右子树的深度较大值 + 1 }
}