Leetcode 543: Diameter of Binary Tree

问题描述:
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.

思路:
最长路径(diameter)分两种情况:
case 1: 最长路径跨越根节点:左子树高度+右子树高度+2
case 2:最长路径不跨越根节点:拆成两个子问题,分别以左右孩子为根,求较大者
最终结果=max(case1,case2)

代码如下:

class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        if(root==null)  return 0;
        int leftHeight=height(root.left);  //height of the left subtree
        int rightHeight=height(root.right);  //height of the right subtree
        int leftDiameter=diameterOfBinaryTree(root.left);  //diameter of the left subtree
        int rightDiameter=diameterOfBinaryTree(root.right);  //diameter of the right subtree
        //case 1: cross the root, then longest path = leftHeight+rightHeight+2
        //case 2: do not cross the root, the longest path = max (diameter of left, diameter of right)
        //we need to calculate the maximum of the two cases
        return Math.max(leftHeight+rightHeight+2, Math.max(leftDiameter, rightDiameter));
    }
    
    private int height(TreeNode root){
        if(root==null)  return -1;
        return Math.max(height(root.left), height(root.right))+1;
    }
}

时间复杂度: O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值