/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans = 1;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return ans - 1;
}
private int depth(TreeNode node) {
if (node == null)
return 0;
int L = depth(node.left);
int R = depth(node.right);
ans = Math.max(ans, L + R + 1);
return Math.max(L, R) + 1;
}
}
来源:CSDN
作者:wl1929
链接:https://blog.csdn.net/wl1929/article/details/104478286