资讯专栏INFORMATION COLUMN

[LeetCode] 543. Diameter of Binary Tree

Y3G / 2068人阅读

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.

Example:
Given a binary tree

      1
     / 
    2   3
   /      
  4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

Solution
class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return max;
    }
    private int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        max = Math.max(max, left+right);
        return Math.max(left, right)+1;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77276.html

相关文章

  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • LeetCode 精选TOP面试题【51 ~ 100】

    摘要:有效三角形的个数双指针最暴力的方法应该是三重循环枚举三个数字。总结本题和三数之和很像,都是三个数加和为某一个值。所以我们可以使用归并排序来解决这个问题。注意因为归并排序需要递归,所以空间复杂度为 ...

    Clect 评论0 收藏0
  • 力扣(LeetCode)543

    摘要:一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。注意两结点之间的路径长度是以它们之间边的数目表示。 题目地址:https://leetcode-cn.com/probl...题目描述:给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。 示例 :给定二叉树 1 / ...

    stormjun 评论0 收藏0
  • LeetCode 536. Construct Binary Tree from String 从带

    摘要:题意从一个带括号的字符串,构建一颗二叉树。其中当而时,展示为一个空的括号。同时要考虑负数的情况,所以在取数字的时候,必须注意所在位置。遇到则从栈中出元素。最后中的元素就是,返回栈顶元素即可。 LeetCode 536. Construct Binary Tree from String You need to construct a binary tree from a string ...

    tabalt 评论0 收藏0
  • LeetCode 104 Maximum Depth of Binary Tree 二叉树最大深度

    LeetCode 104 Maximum Depth of Binary Tree难度:Easy 题目描述:找到一颗二叉树的最深深度。Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down ...

    PiscesYE 评论0 收藏0

发表评论

0条评论

Y3G

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<