首页 > 其他 > 详细

#树#二叉树的直径

时间:2020-07-15 01:03:06      阅读:54      评论:0      收藏:0      [点我收藏+]

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

 

#树#二叉树的直径

原文:https://www.cnblogs.com/lyr-2000/p/13302184.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!