Title

#树#二叉树的直径

选自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;
    }
}

 

posted @ 2020-07-14 22:12  .geek  阅读(156)  评论(0编辑  收藏  举报