[leetcode]543. Diameter of Binary Tree二叉树的直径

Posted stAr_1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]543. Diameter of Binary Tree二叉树的直径相关的知识,希望对你有一定的参考价值。

题目中的直径定义为:

任意两个节点的最远距离

没想出来,看的答案

思路是:diameter = max(左子树diameter,右子树diameter,(左子树深度+右子树深度+1))

遍历并更新结果

int res = 1;
    public int diameterOfBinaryTree(TreeNode root) {
        helper(root);
        return res-1;
    }
    public int[] helper(TreeNode root)
    {
        //两个量分别是节点深度,节点最大diameter
        if (root==null) return new int[]{0,0};
        int cur = 0;
        int[] l = helper(root.left);
        int[] r = helper(root.right);
        cur = Math.max(Math.max(l[1],r[1]),l[0]+r[0]+1);
        res = Math.max(res,cur);
        return new int[]{Math.max(l[0],r[0])+1,cur};
    }

 

以上是关于[leetcode]543. Diameter of Binary Tree二叉树的直径的主要内容,如果未能解决你的问题,请参考以下文章

leetcode_easy543. Diameter of Binary Tree

LeetCode 543. Diameter of Binary Tree 解题笔记

LeetCode 543. Diameter of Binary Tree 解题笔记

[leetcode-543-Diameter of Binary Tree]

Leetcode 543: Diameter of Binary Tree

leetcode 543. Diameter of Binary Tree