1. FlyPython首页
  2. 数据结构与算法
  3. leetcode题解

「LeetCode每日一题」——543. 二叉树的直径

543. 二叉树的直径

链接:https://leetcode-cn.com/problems/diameter-of-binary-tree/
难度:简单

题目

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

示例 :
给定二叉树

     1
    / \
   2   3
  / \     
 4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

思路

根据这道题的题意,直径就是求路径经过节点数的最大值减一。那么这道题就是从任意节点作为起点,从其左儿子和右儿子向下遍历的路径,就可以拼接得到路径,而路径长度最大值减一就是直径。

方案代码

解决方法:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.ans = 1
        def depth(node):
            # 访问到空节点了,返回0
            if not node: return 0
            # 左儿子为根的子树的深度
            L = depth(node.left)
            # 右儿子为根的子树的深度
            R = depth(node.right)
            # 计算d_node即L+R+1 并更新ans
            self.ans = max(self.ans, L+R+1)
            # 返回该节点为根的子树的深度
            return max(L, R) + 1

        depth(root)
        return self.ans - 1

原创文章,作者:flypython,如若转载,请注明出处:http://flypython.com/algorithm/leetcode/216.html