美文网首页LeetCode
LeetCode 543. 二叉树的直径

LeetCode 543. 二叉树的直径

作者: 桐桑入梦 | 来源:发表于2020-03-10 12:02 被阅读0次

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

示例 :
给定二叉树
1
/ \
2 3
/ \
4 5

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]
注意:两结点之间的路径长度是以它们之间边的数目表示。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int diameter = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        deep(root);
        return diameter;
    }
    private int deep( TreeNode root ){
        if( root == null ) 
            return 0;
        int length1 = deep(root.left);
        int length2 = deep(root.right);
        diameter = Math.max( length1 + length2, diameter );
        return length1 > length2 ? length1 + 1 : length2 + 1;
    }
}

相关文章

  • LeetCode 543. 二叉树的直径

    给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结...

  • leetcode 543. 二叉树的直径

    题目描述 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可...

  • tag9:树 二叉树的直径

    leetcode543. 二叉树的直径[https://leetcode-cn.com/problems/diam...

  • LeetCode | 0543. Diameter of Bin

    LeetCode 0543. Diameter of Binary Tree二叉树的直径【Easy】【Python...

  • 543. 二叉树的直径

    原题 https://leetcode-cn.com/problems/diameter-of-binary-tr...

  • 543.二叉树的直径

    解题思路 一条路径的长度为该路径经过的节点数减一,所以求直径(即求路径长度的最大值)等效于求路径经过节点数的最大值...

  • 543. 二叉树的直径

    解法

  • 543. 二叉树的直径

    给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可...

  • 543. 二叉树的直径

    一 题目: 二 思路: 分析下,二叉树的最长路径某个结点的左孩子最大深度加右孩子的最大深度 我们只需要找出每一个节...

  • 【LeetCode】二叉树的直径

    题目描述: https://leetcode-cn.com/problems/diameter-of-binary...

网友评论

    本文标题:LeetCode 543. 二叉树的直径

    本文链接:https://www.haomeiwen.com/subject/cdcwdhtx.html