543. Diameter of Binary Tree

问题描述

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.

思路

  • 建一个全局变量count,存当前最大值,并且不受到recursive的影响
  • 在大方法里,传root,返回count
  • 用一个recursive方法求树的高度,如果nodeNone,返回0;每传进一个node, 先拿到左右两边的subtree分别的高leftrightcount = max(count, left + right);返回max(left, right)+1
class Solution:
    count = 0
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.getH(root)
        return self.count

    def getH(self, node):

        if not node:
            return 0
        left = self.getH(node.left)
        right = self.getH(node.right)
        self.count = max(self.count, left + right)     #update count
        return max(left, right)+1

你可能感兴趣的:(543. Diameter of Binary Tree)