选自LeetCode 的题目
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int diameterOfBinaryTree(TreeNode root) { if(root == null) return 0; result = Math.max(result,height(root.left)+height(root.right)); return result - 1; } int result = 0; int height(TreeNode h) { if(h==null) return 0; int l = height(h.left); int r = height(h.right); result = Math.max(result,l+r+1); return Math.max(l,r)+1; } }