Optimize finding diameter of binary tree in Python

后端 未结 2 1794
一整个雨季
一整个雨季 2020-12-18 13:43

I\'m wondering how I can optimally find the diameter (or longest path between any two leaf nodes) of a binary tree. I have the basic solution below, but the second solution

相关标签:
2条回答
  • 2020-12-18 14:00

    Python supports multiple return values, so you don't need pointer arguments like in C or C++. Here's a translation of the code:

    def diameter_height(node):
        if node is None:
            return 0, 0
        ld, lh = diameter_height(node.left)
        rd, rh = diameter_height(node.right)
        return max(lh + rh + 1, ld, rd), 1 + max(lh, rh)
    
    def find_tree_diameter(node):
        d, _ = diameter_height(node)
        return d
    

    The function diameter_height returns the diameter and the height of the tree, and find_tree_diameter uses it to just compute the diameter (by discarding the height).

    The function is O(n), no matter the shape of the tree. The original function is O(n^2) in the worst case when the tree is very unbalanced because of the repeated height calculations.

    0 讨论(0)
  • 2020-12-18 14:20

    Simple Python 3 solution

    def findDepth(root):
    
        if root is None:
            return 0
    
        return 1 + max(findDepth(root.left), findDepth(root.right))
    
    class Solution:
        def diameterOfBinaryTree(self, root: TreeNode) -> int:
    
            if root is None:
                return 0
    
            left = findDepth(root.left)
            right = findDepth(root.right)
    
            ldia = self.diameterOfBinaryTree(root.left)
            rdia = self.diameterOfBinaryTree(root.right)
    
    
            return max(left+right, max(ldia, rdia))
    
    0 讨论(0)
提交回复
热议问题