Sakura

sakura

博客园 首页 新随笔 联系 订阅 管理

选自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 on 2020-07-14 22:12  .geek  阅读(158)  评论(0编辑  收藏  举报