Leetcode-Easy 543. Diameter of Binary Tree

时间:2022-05-08
本文章向大家介绍Leetcode-Easy 543. Diameter of Binary Tree,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

543. Diameter of Binary Tree

  • 描述: 求二叉树最长路径长度
  • 思路: 深度优先搜索
  • 代码
# 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):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.ans=1
        def depth(node):
            if not node:return 0
            L=depth(node.left)
            R=depth(node.right)
            self.ans=max(self.ans,L+R+1)
            return max(L,R)+1
        
        depth(root)
        return self.ans-1