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

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 in python:

# 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:
        max_len = 0
        def traverse(root):
            if root == None:
                return 0
            else:
                dleft = traverse(root.left)
                dright = traverse(root.right)
                temp = 1+max(dleft, dright)
                nonlocal max_len
                if dleft+dright > max_len:
                    max_len = dleft+dright
                return temp
        traverse(root)
        return max_len
最后修改日期: 2021年2月2日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。