leetcode 找到树中距离最大的两个结点,Python实现

来源:互联网 发布:成都租房 知乎 编辑:程序博客网 时间:2024/05/22 01:30

题目:

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.

(Note: 两个结点之间的距离=两个结点之间 “边”(即连线)的数目)


思路:

1. 计算以当前点为根结点时,树的最大深度;

2. 选出当前结点,以及其左、右子结点距离最大者;

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def diameterOfBinaryTree(self, root):        """        :type root: TreeNode        :rtype: int        """        if not root:            return 0        max_dia_left = self.diameterOfBinaryTree(root.left)        max_dia_right = self.diameterOfBinaryTree(root.right)        max_dia = max(self.get_depth(root.left)+self.get_depth(root.right),max_dia_left,max_dia_right)  # max: 1.当前结点最大距离;2.左、右子结点的最大距离        return max_dia            def get_depth(self,root):  #计算以当前结点为根时,树的最大深度;        if not root:            return 0        else:            return max(1+self.get_depth(root.left),1+self.get_depth(root.right))


阅读全文
0 0
原创粉丝点击