Tree——No.543 Diameter of Binary Tree

Problem:

Given a binary tree, you need to compute 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.

Explanation:

计算二叉树的直径,直径就是从一个结点到另一个结点最长距离,距离是指结点的边数。

My Thinking:

直径一定是两个叶子结点之间的路径,从每个叶子开始记录每个结点到叶子的最大长度,每次更新经过当前结点的最长路径即可。

My Solution:

class Solution {
    private int diameter=0;
    public int diameterOfBinaryTree(TreeNode root) {
        recursive(root);
        return diameter;
    }
     public int recursive(TreeNode root) {
       if(root==null)
            return 0;
        int leftmax=recursive(root.left);
        int rightmax=recursive(root.right);
        int currentmax=leftmax+rightmax;
        if(currentmax>diameter)
            diameter=currentmax;
        return Math.max(leftmax,rightmax)+1;
    }
}

Optimum Thinking:

Optimum Solution:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值