Likou 543. Diameter of a binary tree (python)

Title source: 543. Diameter of binary tree
ideas:
Key points: 1. How to find the path length between two leaf nodes:

The path between two leaf nodes = the sum of the depths of the left and right sons of the root node (the number of layers of the current node, starting from this node and looking down, at most a few nodes can be found, and its depth is just a few)
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
python code:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.res = 0
        def dps(root):
            if not root:
                return 0
            left = dps(root.left)
            right = dps(root.right)
            self.res = max(left+right+1, self.res)
            return max(left, right) + 1
        dps(root)
        return self.res - 1

insert image description here

Reference link: LeetCode0543:
Diameter of Binary Tree 543. Diameter of Binary Tree [LeetCode Official Problem Solution]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324354949&siteId=291194637